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

import com.tykj.dev.config.GlobalMap;
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.*;
import com.tykj.dev.device.task.utils.TaskUtils;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.base.BusinessEnum;
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.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
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);
        Page<TaskUserVo> taskUserVos1 = PageUtil.getPerPage(taskSelectVo.getPage(), taskSelectVo.getSize(), taskUserVos, taskSelectVo.getPageable());
        Map<String,Object> map = new HashMap<>();
        Map<Integer,String> businessMap = GlobalMap.getBusinessMap();
        Set<Integer> businessType = taskUserVos.stream().map(TaskUserVo::getBusinessType).collect(Collectors.toSet());
        map.put("pages",taskUserVos1);
        map.put("businessTypes",businessType.stream().map(integer -> new BusinessTypeVo(integer,businessMap.get(integer))).collect(Collectors.toList()));
        return ResultUtil.success(map);
    }

    @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 @Validated 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 @Validated 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,Comparator.nullsLast(Date::compareTo)).reversed())
                .collect(Collectors.toList());
        return ResultUtil.success(taskLogUserVoList);
    }

    @ApiOperation(value = "根据bill查询业务日志", notes = "可以通过这个接口查询查询业务日志")
    @GetMapping("/manage/detail/log/bill/{id}")
    public ResponseEntity selectBillLog(@PathVariable("id") int bill) {

       Task taskEn= taskDao.findByBillIdAndBusinessType(bill, BusinessEnum.CONFIRM_CHECK_STAT.id).get();

        //添加当前业务日志
        List<TaskLogUserVo> taskLogUserVos = taskLogService.getByTaskId(taskEn.getId());
        //查询所有子业务
        List<TaskBto> taskBtos = taskDao.findAll().stream()
                .filter(task -> task.getNodeIdDetail() != null && task.getNodeIdDetail().contains("." + taskEn.getId() + "."))
                .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,Comparator.nullsLast(Date::compareTo)).reversed())
                .collect(Collectors.toList());
        return ResultUtil.success(taskLogUserVoList);
    }

    @ApiOperation(value = "核查详情查询业务日志", notes = "可以通过这个接口查询查询业务日志")
    @GetMapping("/manage/detail/log/bill/details/{id}")
    public ResponseEntity selectBillLog7(@PathVariable("id") int bill) {

        Task taskEn= taskDao.findByBillIdAndBusinessType(bill, BusinessEnum.CONFIRM_CHECK_DETAIL.id).get();

        //添加当前业务日志
        List<TaskLogUserVo> taskLogUserVos = taskLogService.getByTaskId(taskEn.getId());
        //查询所有子业务
        List<TaskBto> taskBtos = taskDao.findAll().stream()
                .filter(task -> task.getNodeIdDetail() != null && task.getNodeIdDetail().contains("." + taskEn.getId() + "."))
                .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,Comparator.nullsLast(Date::compareTo)).reversed())
                .collect(Collectors.toList());
        return ResultUtil.success(taskLogUserVoList);
    }

    @ApiOperation(value = "查询所有业务日志", notes = "可以通过这个接口查询业务日志")
    @PostMapping("/manage/detail/logs")
    public ResponseEntity selectAllLogs(@RequestBody TaskLogSelectVo taskLogSelectVo){
        return ResponseEntity.ok( PageUtil.getPerPage(taskLogSelectVo.getPage(), taskLogSelectVo.getSize(), taskLogService.getAllByTime(taskLogSelectVo), taskLogSelectVo.getPageable()));
    }
}
