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.TimeControlTaskSendDetailMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskSendMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskSubscribeMapper;
import com.pcloud.book.timecontrol.vo.request.TimeControlTaskItemVO;
import com.pcloud.common.constant.CacheConstant;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
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.*;
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;
    @Autowired
    private TimeControlTaskSendDetailMapper  timeControlTaskSendDetailMapper;


    @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 = timeControlTaskSendDetailMapper.getTaskItemSendCount(startTime,endTime,robotWxId,taskName,sendContent);
        if (count <= 0) {
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        list = timeControlTaskSendDetailMapper.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();
                            String key = CacheConstant.BOOK + "GET_RESOURCE_INFO:" + resourceId;
                            ResourceDTO resourceDTO = JedisClusterUtils.getJson(key, ResourceDTO.class);
                            if (null == resourceDTO) {
                                Map<Long, ResourceDTO> map = resourceConsr.mapByIds(Arrays.asList(resourceId));
                                resourceDTO = map.get(resourceId);
                                if (null != resourceDTO) {
                                    JedisClusterUtils.setJson(key, resourceDTO);
                                }
                            }
                            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, String startTime, String endTime) {
        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 = timeControlTaskSendDetailMapper.getTaskItemSendUserCount(wxIds, taskItemId, robotWxId, startTime, endTime);
        if (count <= 0) {
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }
        list = timeControlTaskSendDetailMapper.listTaskItemSendUser4Pcloud(currentPage * numPerPage, numPerPage, wxIds, taskItemId, robotWxId, startTime, endTime);
        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 = timeControlTaskSendDetailMapper.todayTaskSendCount();
        Integer todayTaskNotSendCount = timeControlTaskSendMapper.todayTaskNotSendCount();
        todayTaskSendDto.setTodaySendCount(todayTaskSendCount);
        todayTaskSendDto.setTodayNotSendCount(todayTaskNotSendCount);
        return todayTaskSendDto;
    }

    @Override
    public List<String> getTaskSendDateList(String date) {
        List<String> taskSendDateList = timeControlTaskSendDetailMapper.getTaskSendDateList(date);
      /*  //获取sendType=1的时间集合
        List<String> taskSendDateList = timeControlTaskSendMapper.getTaskSendDateList(date);
        if(ListUtils.isEmpty(taskSendDateList)){
            taskSendDateList=new ArrayList<>();
        }
        //获取sendType=2 pushType=1的时间集合
        date=date+"-01";
        TimeControlTaskItemVO monthDay = taskItemMapper.getMonthDay(date);
        List<Date> betweenDates = getBetweenDates(monthDay.getStartDay(), monthDay.getEndDay());
        for (Date dateStr:betweenDates) {
            String str = DateUtils.formatDate(dateStr, "yyyy-MM-dd");
            if(!ListUtils.isEmpty(taskSendDateList)&&!taskSendDateList.contains(str)){
                taskSendDateList.add(str);
            }
        }
        //获取sendType=2 pushType=2的时间集合
        List<TimeControlTaskItemVO> monthSecondDay=taskItemMapper.getMonthSecondDay(date);
        for (TimeControlTaskItemVO taskItemVO:monthSecondDay) {
            List<Date> betdate = getBetweenDates(taskItemVO.getStartDay(), taskItemVO.getEndDay());
            for(int d=0;d<betdate.size();d++) {
                Calendar betrq = Calendar.getInstance();
                betrq.setTime(betdate.get(d));
                Integer day = betrq.get(Calendar.DAY_OF_WEEK)-1;
                if(day==0){
                    day=7;
                }
                String str1 = DateUtils.formatDate(betrq.getTime(), "yyyy-MM-dd");
                if(!ListUtils.isEmpty(taskSendDateList)&&taskItemVO.getWeekDays().contains(day.toString())&&!taskSendDateList.contains(str1)){
                    taskSendDateList.add(str1);
                }
            }

        }*/
        return taskSendDateList;
    }

    private List<Date> getBetweenDates(Date start, Date end) {
        List<Date> datelist = new ArrayList<Date>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        //tempStart.add(Calendar.DAY_OF_YEAR, 1);//这里可以设置从第二天开始

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        while (tempStart.before(tempEnd)) {
            datelist.add(tempStart.getTime());
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return datelist;
    }


    @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;
    }
}
