package com.hssx.pcbms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hssx.pcbms.constant.Constant;
import com.hssx.pcbms.entity.*;
import com.hssx.pcbms.entity.vo.TaskDTO;
import com.hssx.pcbms.entity.vo.TaskVO;
import com.hssx.pcbms.mapper.*;
import com.hssx.pcbms.service.TaskParticipantsService;
import com.hssx.pcbms.service.TaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hssx.pcbms.util.HttpRespMsg;
import com.hssx.pcbms.util.ListUtil;
import com.hssx.pcbms.util.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 吴涛涛
 * @since 2019-11-11
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Resource
    private TaskMapper taskMapper;
    @Resource
    private TaskParticipantsService taskParticipantsService;
    @Resource
    private TaskDynamicMapper taskDynamicMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private NewsNoticeMapper newsNoticeMapper;
    @Resource
    private NewsNoticeUserMapper newsNoticeUserMapper;

    @Override
    public HttpRespMsg addOrUpdate(Task task, String participantsIdes) {
        HttpRespMsg msg = new HttpRespMsg();
        List<TaskParticipants> taskParticipants = new ArrayList<>();
        if (null == task.getId()) {
            TaskDynamic taskDynamic = new TaskDynamic();
            if (task.getRecipientId() != null) {
                task.setState(1);//已派发
                taskMapper.insert(task);
                taskDynamic.setTaskState(1);//已派发
                taskDynamic.setStateContent(Constant.ALREADY_DISTRIBUTED);
                taskDynamic.setContent(userMapper.selectById(task.getPublishId()).getName() + Constant.TASK_DISTRIBUTE + userMapper.selectById(task.getRecipientId()).getName());
                taskDynamic.setTaskId(task.getId());
                taskDynamicMapper.insert(taskDynamic);
                //给接收人发送消息
                NewsNotice newsNotice = new NewsNotice();
                newsNotice.setNoticeType(2);
//                Integer rafId = Integer.valueOf(task.getId());
//                newsNotice.setRefId(rafId);
                newsNotice.setRafName(task.getName());
                newsNotice.setContent("有新的任务待您接受");
                newsNoticeMapper.insert(newsNotice);
                NewsNoticeUser noticeUser = new NewsNoticeUser();
                noticeUser.setIsRead(0);
                noticeUser.setUserId(task.getRecipientId());
                noticeUser.setNewsId(newsNotice.getId());
                newsNoticeUserMapper.insert(noticeUser);
            } else {
                task.setState(0);//待派发
                taskMapper.insert(task);
                taskDynamic.setTaskState(0);//待派发
                taskDynamic.setStateContent(Constant.TO_BE_DISTRIBUTE);
                taskDynamic.setContent(userMapper.selectById(task.getPublishId()).getName() + Constant.TASK_PULISH);
                taskDynamic.setTaskId(task.getId());
                taskDynamicMapper.insert(taskDynamic);
            }
            if (participantsIdes != null && participantsIdes != "") {
                List<Integer> ids = ListUtil.convertIntegerIdsArrayToList(participantsIdes);
                for (Integer id : ids) {
                    TaskParticipants participants = new TaskParticipants();
                    participants.setTaskId(task.getId());
                    participants.setUserId(id);
                    taskParticipants.add(participants);
                }
                taskParticipantsService.saveBatch(taskParticipants);
            }
        } else {
            Task oldTask = taskMapper.selectById(task.getId());
            TaskDynamic taskDynamic = new TaskDynamic();
            taskDynamic.setTaskId(task.getId());
            if (task.getDelayTime() != null && oldTask.getDelayTime() == null) {
                //添加动态
                taskDynamic.setTaskState(6);//已延期
                taskDynamic.setStateContent(Constant.ALREADY_DELAY);
                taskDynamic.setContent(userMapper.selectById(task.getPublishId()).getName() + Constant.TASK_DELAY + task.getDelayTime());
                taskDynamicMapper.insert(taskDynamic);
            }
            if (task.getRecipientId() != null && oldTask.getRecipientId() == null) {
                task.setState(1);//已派发
                taskDynamic.setTaskState(1);//已派发
                taskDynamic.setStateContent(Constant.ALREADY_DISTRIBUTED);
                taskDynamic.setContent(userMapper.selectById(task.getPublishId()).getName() + Constant.TASK_DISTRIBUTE + userMapper.selectById(task.getRecipientId()).getName());
                taskDynamicMapper.insert(taskDynamic);
                //给接收人发送消息
                NewsNotice newsNotice = new NewsNotice();
                newsNotice.setNoticeType(2);
                newsNotice.setRafName(task.getName());
                newsNotice.setContent("有新的任务待您接受");
                newsNoticeMapper.insert(newsNotice);
                NewsNoticeUser noticeUser = new NewsNoticeUser();
                noticeUser.setIsRead(0);
                noticeUser.setUserId(task.getRecipientId());
                noticeUser.setNewsId(newsNotice.getId());
                newsNoticeUserMapper.insert(noticeUser);
            }
            taskMapper.updateById(task);
            if (participantsIdes != null && participantsIdes != "") {
                taskParticipantsService.remove(new QueryWrapper<TaskParticipants>().eq("task_id", task.getId()));
                List<Integer> ids = ListUtil.convertIntegerIdsArrayToList(participantsIdes);
                for (Integer id : ids) {
                    TaskParticipants participants = new TaskParticipants();
                    participants.setTaskId(task.getId());
                    participants.setUserId(id);
                    taskParticipants.add(participants);
                }
                taskParticipantsService.saveBatch(taskParticipants);
            }
        }
        return msg;
    }

    @Override
    public HttpRespMsg getListByCondition(TaskVO taskVO, PageUtil page) {
        HttpRespMsg msg = new HttpRespMsg();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (taskVO.getType() == 0) {
            //我的任务
            List<Task> tasks = taskMapper.selectList(new QueryWrapper<Task>().eq("recipient_id", taskVO.getUid()));
            List<TaskParticipants> participants = taskParticipantsService.list(new QueryWrapper<TaskParticipants>().eq("user_id", taskVO.getUid()));
            List<String> taskIds = new ArrayList<>();
            if (tasks.size() > 0) {
                taskIds.addAll(tasks.stream().map(Task::getId).collect(Collectors.toList()));
            }
            if (participants.size() > 0) {
                taskIds.addAll(participants.stream().map(TaskParticipants::getTaskId).collect(Collectors.toList()));
            }
            if (taskIds.size() > 0) {
                List<TaskDTO> taskDTOList = taskMapper.selectListByTaskIds(taskIds, taskVO);
                PageInfo<TaskDTO> pageInfo = new PageInfo<>(taskDTOList);
                msg.data = pageInfo;
            }
        } else if (taskVO.getType() == 1) {
            //我发布的
            List<TaskDTO> taskDTOList = taskMapper.selectListByCondition(taskVO);
            PageInfo<TaskDTO> pageInfo = new PageInfo<>(taskDTOList);
            msg.data = pageInfo;
        }
        return msg;
    }

    @Override
    public HttpRespMsg detail(TaskVO taskVO) {
        HttpRespMsg msg = new HttpRespMsg();
        TaskDTO dto = taskMapper.getDetailById(taskVO);
        msg.data = dto;
        return msg;
    }

    @Override
    public HttpRespMsg acceptTask(Task task) {
        HttpRespMsg msg = new HttpRespMsg();
        task.setState(2);//已接受
        taskMapper.updateById(task);
        TaskDynamic dynamic = new TaskDynamic();
        dynamic.setTaskId(task.getId());
        dynamic.setTaskState(2);
        dynamic.setStateContent(Constant.ALREADY_ACCEPT);
        dynamic.setContent(userMapper.selectById(task.getRecipientId()).getName() + Constant.TASK_ACCEPTED);
        taskDynamicMapper.insert(dynamic);
        return msg;
    }

    @Override
    public HttpRespMsg taskInvalidChecking() {
        List<Task> taskList = taskMapper.selectList(new QueryWrapper<Task>().ne("state", 7).ne("state", 8));
        LocalDateTime now = LocalDateTime.now();
        String format = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(now);
        for (Task task : taskList) {
            if (task.getState() == 6) {
                if (format.compareTo(task.getDelayTime()) >= 0) {
                    task.setState(7);
                    taskMapper.updateById(task);
                    TaskDynamic taskDynamic = new TaskDynamic();
                    taskDynamic.setTaskState(7);//已失效
                    taskDynamic.setStateContent(Constant.ALREADY_INVALID);
                    taskDynamic.setTaskId(task.getId());
                    taskDynamic.setContent("[" + task.getName() + "] " + Constant.ALREADY_INVALID);
                    taskDynamicMapper.insert(taskDynamic);

                }
            } else {
                if (format.compareTo(task.getPlanTime()) >= 0) {
                    task.setState(7);
                    taskMapper.updateById(task);
                    TaskDynamic taskDynamic = new TaskDynamic();
                    taskDynamic.setTaskState(7);//已失效
                    taskDynamic.setStateContent(Constant.ALREADY_INVALID);
                    taskDynamic.setContent("[" + task.getName() + "] " + Constant.ALREADY_INVALID);
                    taskDynamicMapper.insert(taskDynamic);
                }
            }
        }
        return null;
    }

    @Override
    public HttpRespMsg del(Task task) {
        HttpRespMsg msg = new HttpRespMsg();
        task.setState(8);//软删除
        taskMapper.updateById(task);
        return msg;
    }
}
