package com.pcloud.book.timecontrol.biz.impl;

import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.timecontrol.biz.TaskBiz;
import com.pcloud.book.timecontrol.biz.TaskCompletedBiz;
import com.pcloud.book.timecontrol.biz.TaskSubscribeBiz;
import com.pcloud.book.timecontrol.dto.ReplyMessageDto;
import com.pcloud.book.timecontrol.dto.SubscribeTaskUserDTO;
import com.pcloud.book.timecontrol.dto.TaskCompletedDto;
import com.pcloud.book.timecontrol.dto.TaskItemSendDto;
import com.pcloud.book.timecontrol.dto.TaskProgressDTO;
import com.pcloud.book.timecontrol.dto.TaskProgressItemDTO;
import com.pcloud.book.timecontrol.dto.TaskSendUserDto;
import com.pcloud.book.timecontrol.dto.TodayTaskSendDto;
import com.pcloud.book.timecontrol.entity.TimeControlTask;
import com.pcloud.book.timecontrol.entity.TimeControlTaskPrize;
import com.pcloud.book.timecontrol.mapper.TaskPrizeMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlReplyMessageMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskItemMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskSendMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskSubscribeMapper;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.pcloud.labelcenter.label.service.LabelService;
import com.pcloud.wechatgroup.group.dto.GroupUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @date: 2020年01月30日 14:20
 * @Author: Zcy
 * @Descprition
 */
@Component("taskCompletedBiz")
@Slf4j
public class TaskCompletedBizImpl implements TaskCompletedBiz {

    private final static Logger LOGGER = LoggerFactory.getLogger(TaskCompletedBizImpl.class);

    @Autowired
    private TimeControlTaskMapper taskMapper;
    @Autowired
    private TimeControlTaskItemMapper taskItemMapper;
    @Autowired
    private TimeControlReplyMessageMapper replyMessageMapper;
    @Autowired
    private TimeControlTaskSubscribeMapper taskSubscribeMapper;
    @Autowired
    private TimeControlTaskSendMapper timeControlTaskSendMapper;
    @Autowired
    private LabelService labelService;
    @Autowired
    private TaskSubscribeBiz taskSubscribeBiz;
    @Autowired
    private TaskBiz taskBiz;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private TaskPrizeMapper taskPrizeMapper;
    //@Autowired
    //private PcloudKeywordService pcloudKeywordService;
    @Autowired
    private ResourceConsr resourceConsr;


    @Override
    public PageBeanNew<TaskCompletedDto> listTaskCompleted4Pcloud(Integer currentPage, Integer numPerPage, String taskName, Integer proLabelId, Integer depLabelId, Integer purLabelId) {
        List<TaskCompletedDto> list = new ArrayList<>();

        Integer count = taskMapper.getTaskCompletedCount(taskName, proLabelId, depLabelId, purLabelId);
        if (count <= 0) {
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        list = taskMapper.listTaskCompleted4Pcloud(currentPage * numPerPage, numPerPage,taskName, proLabelId, depLabelId, purLabelId);
        return new PageBeanNew<>(currentPage, numPerPage, count, list);
    }

    @Override
    public PageBeanNew<SubscribeTaskUserDTO> listTaskSubscribeUser4Pcloud(Integer currentPage, Integer numPerPage, String search, Integer taskId,Integer subscribeType) {
        List<SubscribeTaskUserDTO> list = new ArrayList<>();
        List<String> wxIds=new ArrayList<>();
        if(StringUtil.isNotBlank(search)){
            wxIds=wechatGroupConsr.getByUserQuery(search);
            if (ListUtils.isEmpty(wxIds)){
                return new PageBeanNew<>(currentPage, numPerPage, 0, list);
            }
        }
        Integer count = taskMapper.getSubscribeCount(search,taskId,subscribeType,wxIds);
        if (count <= 0) {
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        //按照完成次数降序
        list = taskMapper.listTaskSubscribeUser4Pcloud(currentPage * numPerPage, numPerPage,search,taskId,subscribeType,wxIds);
        if(ListUtils.isEmpty(list)){
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        fillUserCompletedList(taskId, list);

        return new PageBeanNew<>(currentPage, numPerPage, count, list);
    }

    private void fillUserCompletedList(Integer taskId, List<SubscribeTaskUserDTO> list) {

        List<String> wxIdList = list.stream().map(a -> a.getWxUserId()).distinct().collect(Collectors.toList());
        //未完成次数
        List<SubscribeTaskUserDTO> taskUserSendList=timeControlTaskSendMapper.getTaskNoCompletedCount(wxIdList,taskId);
        Map<String, Integer> noCompletedMap=new HashMap<>();
        if(!ListUtils.isEmpty(taskUserSendList)){
            noCompletedMap= taskUserSendList.stream().collect(Collectors.toMap(a -> a.getWxUserId(), a -> a.getNoCompletedCount(), (k1, k2) -> k2));
        }
        Map<String, GroupUserDTO> userDTOMap = wechatGroupConsr.mapWxUserInfoByWxIdList(wxIdList);
        for (SubscribeTaskUserDTO subscribeTaskUserDTO : list) {
            //填充未完成次数
            if(MapUtils.isNotEmpty(noCompletedMap) && noCompletedMap.containsKey(subscribeTaskUserDTO.getWxUserId())){
                Integer noCompletedCount = noCompletedMap.get(subscribeTaskUserDTO.getWxUserId());
                subscribeTaskUserDTO.setNoCompletedCount(noCompletedCount);
            }else{
                subscribeTaskUserDTO.setNoCompletedCount(0);
            }
            //填充用户信息
            if(MapUtils.isNotEmpty(userDTOMap) && userDTOMap.containsKey(subscribeTaskUserDTO.getWxUserId())){
                GroupUserDTO groupUserDTO = userDTOMap.get(subscribeTaskUserDTO.getWxUserId());
                if(null!=groupUserDTO){
                    subscribeTaskUserDTO.setNickName(groupUserDTO.getNickName());
                    subscribeTaskUserDTO.setHeadPic(groupUserDTO.getHeadPic());
                    subscribeTaskUserDTO.setSex(groupUserDTO.getSex());
                }
            }
        }
    }

    @Override
    public PageBeanNew<TaskItemSendDto> listTaskItemSendRecord4Pcloud(Integer currentPage, Integer numPerPage, String startTime, String endTime, String robotWxId, String taskName, String sendContent, String search) {
        List<TaskItemSendDto> list = new ArrayList<>();

        Integer count = timeControlTaskSendMapper.getTaskItemSendCount(startTime,endTime,robotWxId,taskName,sendContent);
        if (count <= 0) {
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        list = timeControlTaskSendMapper.listTaskItemSendRecord4Pcloud(currentPage * numPerPage, numPerPage,startTime,endTime,robotWxId,taskName,sendContent);
        log.info("发送记录查询条数="+list.size());
        if(ListUtils.isEmpty(list)){
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        fillSendRecordList(list);
        return new PageBeanNew<>(currentPage, numPerPage, count, list);
    }

    private void fillSendRecordList(List<TaskItemSendDto> list) {
        //批量查询机器人信息
        List<String> robotIdlist = list.stream().map(TaskItemSendDto::getRobotWxId).distinct().collect(Collectors.toList());
        Map<String, GroupUserDTO> robotMap = wechatGroupConsr.mapRobotInfoByIdList(robotIdlist);

        //批量查询发送内容
        List<Integer> taskItemIdList = list.stream().map(TaskItemSendDto::getTaskItemId).distinct().collect(Collectors.toList());
        List<ReplyMessageDto> replyMessageDtos = replyMessageMapper.list4TaskItemList(taskItemIdList, 0);
        Map<Integer, List<ReplyMessageDto>> replyMap = new HashMap<>();
        if (!ListUtils.isEmpty(replyMessageDtos)) {
            replyMap = replyMessageDtos.stream().collect(Collectors.groupingBy(ReplyMessageDto::getTaskItemId));
        }
        for (TaskItemSendDto taskItemSendDto : list) {
            if (MapUtils.isNotEmpty(robotMap) && robotMap.containsKey(taskItemSendDto.getRobotWxId())) {
                GroupUserDTO groupUserDTO = robotMap.get(taskItemSendDto.getRobotWxId());
                if (null != groupUserDTO) {
                    taskItemSendDto.setRobotName(groupUserDTO.getNickName());
                }
            }
            if (MapUtils.isNotEmpty(replyMap) && replyMap.containsKey(taskItemSendDto.getTaskItemId())) {
                List<ReplyMessageDto> replyMessageDtoList = replyMap.get(taskItemSendDto.getTaskItemId());
                if (!ListUtils.isEmpty(replyMessageDtoList)) {
                    replyMessageDtoList.forEach(message -> {
                        if (ReplyTypeEnum.RESOURCE.value.equals(message.getReplyType())) {
                            Long resourceId = message.getResourceId();
                            Map<Long, ResourceDTO> map = resourceConsr.mapByIds(Arrays.asList(resourceId));
                            ResourceDTO resourceDTO = map.get(resourceId);
                            if (resourceDTO != null) {
                                message.setResourceName(resourceDTO.getResourceName());
                                message.setResourceUrl(resourceDTO.getFileUrl());
                                message.setFileType(resourceDTO.getFileType());
                                message.setFileSize(resourceDTO.getFileSize());
                                message.setResourceTypeCode(resourceDTO.getTypeCode());
                            }
                        }
                    });
                }
                taskItemSendDto.setReplyMessageList(replyMessageDtoList);
            }
        }
    }

    @Override
    public PageBeanNew<TaskSendUserDto> listTaskItemSendUser4Pcloud(Integer currentPage, Integer numPerPage, Integer taskItemId, String search, String robotWxId) {
        List<TaskSendUserDto> list = new ArrayList<>();
        List<String> wxIds = new ArrayList<>();
        if (StringUtil.isNotBlank(search)) {
            wxIds = wechatGroupConsr.getByUserQuery(search);
            if (ListUtils.isEmpty(wxIds)){
                return new PageBeanNew<>(currentPage, numPerPage, 0, list);
            }
        }
        Integer count = timeControlTaskSendMapper.getTaskItemSendUserCount(wxIds, taskItemId, robotWxId);
        if (count <= 0) {
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        list = timeControlTaskSendMapper.listTaskItemSendUser4Pcloud(currentPage * numPerPage, numPerPage, wxIds, taskItemId, robotWxId);
        if (ListUtils.isEmpty(list)) {
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        List<String> wxIdList = list.stream().map(TaskSendUserDto::getWxUserId).collect(Collectors.toList());
        Map<String, GroupUserDTO> userDTOMap = wechatGroupConsr.mapWxUserInfoByWxIdList(wxIdList);
        list.forEach(item -> {
            String wxUserId = item.getWxUserId();
            if (userDTOMap != null && userDTOMap.get(wxUserId) != null) {
                GroupUserDTO groupUserDTO = userDTOMap.get(wxUserId);
                item.setNickName(groupUserDTO.getNickName());
                item.setHeadPic(groupUserDTO.getHeadPic());
                item.setSex(groupUserDTO.getSex());
            }
        });
        return new PageBeanNew<>(currentPage, numPerPage, count, list);
    }

    @Override
    public TodayTaskSendDto getTodayTaskSend() {
        TodayTaskSendDto todayTaskSendDto=new TodayTaskSendDto();
        Integer todayTaskSendCount = timeControlTaskSendMapper.todayTaskSendCount();
        Integer todayTaskNotSendCount = timeControlTaskSendMapper.todayTaskNotSendCount();
        todayTaskSendDto.setTodaySendCount(todayTaskSendCount);
        todayTaskSendDto.setTodayNotSendCount(todayTaskNotSendCount);
        return todayTaskSendDto;
    }

    @Override
    public List<String> getTaskSendDateList(String date) {
        List<String> taskSendDateList = timeControlTaskSendMapper.getTaskSendDateList(date);
        return taskSendDateList;
    }

    @Override
    public TaskProgressDTO getUserTaskProgress(Integer taskId, String wxUserId) throws BizException {
        TaskProgressDTO taskProgressDTO = new TaskProgressDTO();
        taskProgressDTO.setWxUserId(wxUserId);
        TimeControlTask timeControlTask = taskMapper.selectByPrimaryKey(taskId);
        if (null == timeControlTask) {
            return taskProgressDTO;
        }
        taskProgressDTO.setTaskName(timeControlTask.getTaskName());
        taskProgressDTO.setTaskIntroduce(timeControlTask.getTaskIntroduce());
        GroupUserDTO groupUserDTO = wechatGroupConsr.getWxUserInfoByWxUserId(wxUserId);
        if (null != groupUserDTO) {
            taskProgressDTO.setNickname(groupUserDTO.getNickName());
            taskProgressDTO.setHeadPic(groupUserDTO.getHeadPic());
        }
        TaskProgressDTO progressDTO = taskSubscribeMapper.getSubscribeStatics(taskId);
        if (null != progressDTO) {
            taskProgressDTO.setSubscribeCount(progressDTO.getSubscribeCount());
            taskProgressDTO.setFinishCount(progressDTO.getFinishCount());
        }
        taskProgressDTO.setTaskCount(taskItemMapper.getTaskItemCount(taskId));
        List<TaskProgressItemDTO> itemList = timeControlTaskSendMapper.getUserTaskItemProgress(taskId, wxUserId);
        taskProgressDTO.setItemList(itemList);
        Integer finishTaskCount = 0;
        if (!ListUtils.isEmpty(itemList)) {
            for(TaskProgressItemDTO dto : itemList) {
                if (null != dto.getCompleteState() && dto.getCompleteState()) {
                    finishTaskCount += 1;
                }
            }
        }
        taskProgressDTO.setFinishTaskCount(finishTaskCount);
        TimeControlTaskPrize prize = taskPrizeMapper.getByTaskId(taskId, 0);
        if (null != prize && null != prize.getTotalPrizeNum()) {
            taskProgressDTO.setPrizeTaskCount(prize.getTotalPrizeNum());
        }
        return taskProgressDTO;
    }
}
