package com.tykj.dev.device.task.controller;

import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.task.repository.TaskDao;
import com.tykj.dev.device.task.service.TaskLogService;
import com.tykj.dev.device.task.service.TaskService;
import com.tykj.dev.device.task.subject.bto.TaskBto;
import com.tykj.dev.device.task.subject.domin.Task;
import com.tykj.dev.device.task.subject.vo.TaskLogUserVo;
import com.tykj.dev.device.task.subject.vo.TaskSelectVo;
import com.tykj.dev.device.task.subject.vo.TaskTopVo;
import com.tykj.dev.device.task.subject.vo.TaskUserVo;
import com.tykj.dev.device.task.utils.TaskUtils;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.utils.PageUtil;
import com.tykj.dev.misc.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dengdiyi
 */
@RestController
@Api(tags = "业务模块",description = "业务模块")
@AutoDocument
@RequestMapping("/business")
public class TaskController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private TaskUtils taskUtils;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private TaskDao taskDao;

    @ApiOperation(value = "业务分页查询", notes = "可以通过这个接口分页查询业务")
    @RequestMapping(method = RequestMethod.POST, value = "/manage/summary", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity getTaskPage(@RequestBody TaskSelectVo taskSelectVo) {
        List<TaskUserVo> taskUserVos = taskService.getManageList(taskSelectVo);
        return ResultUtil.success(PageUtil.getPerPage(taskSelectVo.getPage(), taskSelectVo.getSize(), taskUtils.orderByTopDescAndReadAsc(taskUserVos), taskSelectVo.getPageable()));
    }

    @ApiOperation(value = "业务跟踪待办列表查询", notes = "可以通过这个接口查询业务")
    @RequestMapping(method = RequestMethod.POST, value = "/getTaskList", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity getTaskList(@RequestBody TaskSelectVo taskSelectVo) {
        List<TaskUserVo> taskUserVos = taskService.getList(taskSelectVo);
        return ResultUtil.success(taskUtils.orderByTopDescAndReadAsc(taskUserVos));
    }

    @ApiOperation(value = "置顶设置", notes = "可以通过这个接口置顶业务")
    @RequestMapping(method = RequestMethod.PUT, value = "/setTop", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity setTop(@RequestBody TaskTopVo taskTopVo) {
        TaskBto taskBto = taskService.get(taskTopVo.getTaskId());
        Integer userId = userUtils.getCurrentUserId();
        List<Integer> userIds = taskBto.getTopFlagDetailList();
        if (taskTopVo.getTopFlag() == 1) {
            if (userIds != null) {
                taskBto.getTopFlagDetailList().add(userId);
            }
        }
        if (taskTopVo.getTopFlag() == 0) {
            if (userIds != null && userIds.contains(userId)) {
                userIds.removeAll(new ArrayList<>(Collections.singletonList(userId)));
            }
        }
        Task task = taskService.update(taskBto);
        return ResultUtil.success(task.parse2Bto().toVo());
    }

    @ApiOperation(value = "是否已读设置", notes = "可以通过这个接口设置业务的是否已读")
    @PostMapping("/setRead")
    public ResponseEntity setRead(@RequestBody TaskTopVo taskTopVo) {
        TaskBto taskBto = taskService.get(taskTopVo.getTaskId());
        Integer userId = userUtils.getCurrentUserId();
        List<Integer> userIds = taskBto.getUserReadDetailList();
        if (taskTopVo.getTopFlag() == 1) {
            if (userIds != null) {
                taskBto.getUserReadDetailList().add(userId);
            }
        }
        if (taskTopVo.getTopFlag() == 0) {
            if (userIds != null && userIds.contains(userId)) {
                userIds.removeAll(new ArrayList<>(Collections.singletonList(userId)));
            }
        }
        Task task = taskService.update(taskBto);
        return ResultUtil.success(task.parse2Bto().toVo());
    }

    @ApiOperation(value = "查询业务日志", notes = "可以通过这个接口查询查询业务日志")
    @GetMapping("/manage/detail/log/{id}")
    public ResponseEntity selectLog(@PathVariable("id") int taskId) {
        //添加当前业务日志
        List<TaskLogUserVo> taskLogUserVos = taskLogService.getByTaskId(taskId);
        //查询所有子业务
        List<TaskBto> taskBtos = taskDao.findAll().stream()
                .filter(task -> task.getNodeIdDetail() != null && task.getNodeIdDetail().contains("." + taskId + "."))
                .map(Task::parse2Bto)
                .collect(Collectors.toList());
        //添加子业务日志
        if (taskBtos.size() > 0) {
            taskBtos.forEach(taskBto -> taskLogUserVos.addAll(taskLogService.getByTaskId(taskBto.getId())));
        }
        //按日志时间排序
        List<TaskLogUserVo> taskLogUserVoList = taskLogUserVos.stream()
                .sorted(Comparator.comparing(TaskLogUserVo::getCreateTime))
                .collect(Collectors.toList());
        return ResultUtil.success(taskLogUserVoList);
    }
}
