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

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.weixinclock.biz.WeixinClockPraiseBiz;
import com.pcloud.book.weixinclock.dao.WeixinClockMemberDao;
import com.pcloud.book.weixinclock.dao.WeixinClockPraiseDao;
import com.pcloud.book.weixinclock.dto.GetByMemberAndUserDto;
import com.pcloud.book.weixinclock.dto.ListWeixinClockRankDto;
import com.pcloud.book.weixinclock.dto.RankDto;
import com.pcloud.book.weixinclock.entity.WeixinClockMember;
import com.pcloud.book.weixinclock.entity.WeixinClockPraise;
import com.pcloud.book.weixinclock.vo.request.PraiseForMemberRequestVO;
import com.pcloud.book.weixinclock.vo.response.ListPraiseUserResponseVO;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.readercenter.wechat.entity.WechatUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Describe: 微信打卡点赞逻辑层实现类
 * @Author: zhangdongwei
 * @Date: Create on 9:10 2019/10/23 0023
 */
@Service("weixinClockPraiseBiz")
public class WeixinClockPraiseBizImpl implements WeixinClockPraiseBiz {
    @Autowired
    private WeixinClockPraiseDao weixinClockPraiseDao;
    @Autowired
    private WeixinClockMemberDao weixinClockMemberDao;
    @Autowired
    private ReaderConsr readerConsr;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void praiseForMember(PraiseForMemberRequestVO vo) {
        //根据微信群id和打卡成员id获取打卡成员信息
        WeixinClockMember weixinClockMember = weixinClockMemberDao.getByWxUserId(vo.getWxGroupId(), vo.getWxUserId());
        Optional.ofNullable(weixinClockMember).orElseThrow(() -> new BookBizException(BookBizException.ID_NOT_EXIST, "该打卡成员不存在，不能点赞"));
        if (weixinClockMember.getAllClockDay() <= 0){
            throw new BookBizException(BookBizException.ID_NOT_EXIST, "该打卡成员未打过卡，不能点赞");
        }
        //获取当天零点的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
        GetByMemberAndUserDto dto = new GetByMemberAndUserDto();
        dto.setCreateTime(zero);
        dto.setWechatUserId(vo.getPraiseUserId());
        dto.setWxGroupId(vo.getWxGroupId());
        dto.setWxUserId(vo.getWxUserId());
        WeixinClockPraise oldWeixinClockPraise = weixinClockPraiseDao.getByMemberAndUser(dto);
        WeixinClockPraise weixinClockPraise = PraiseForMemberRequestVO.valueToClockPraise(vo);
        weixinClockPraise.setWeixinClockId(weixinClockMember.getWeixinClockId());
        if (null == oldWeixinClockPraise){
            weixinClockPraise.setIsCancel(1);
            weixinClockPraiseDao.insert(weixinClockPraise);
        }else {
            weixinClockPraise.setId(oldWeixinClockPraise.getId());
            weixinClockPraiseDao.update(weixinClockPraise);
        }
        //点赞或者取消成功， 修改打卡成员得分
        weixinClockMemberDao.updateScore(weixinClockMember.getWeixinClockMemberId(), weixinClockPraise.getIsCancel());
    }

    @Override
    public void fillPraise(List<RankDto> list, ListWeixinClockRankDto listWeixinClockRankDto) {
        if (ListUtils.isEmpty(list)){
            return;
        }
        List<String> wxUserIds = list.stream().map(RankDto::getWxUserId).collect(Collectors.toList());
        if (ListUtils.isEmpty(wxUserIds)){
            return;
        }
        listWeixinClockRankDto.setWxUserIdList(wxUserIds);
        List<WeixinClockPraise> weixinClockPraiseList = weixinClockPraiseDao.getMemberPraise(listWeixinClockRankDto);
        Map<String, List<WeixinClockPraise>> praiseMap = weixinClockPraiseList.stream().collect(Collectors.groupingBy(WeixinClockPraise::getWxUserId));
        Map<String, Boolean> map = new HashMap<>();
        //获取当天零点的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
        for (WeixinClockPraise praise : weixinClockPraiseList){
            if (null == praise.getPraiseUserId()
                    || !listWeixinClockRankDto.getWechatUserId().equals(praise.getPraiseUserId())
                    || map.getOrDefault(praise.getWxUserId(), Boolean.FALSE )|| praise.getCreateTime().before(zero)){
                continue;
            }
            map.put(praise.getWxUserId(), Boolean.TRUE);
        }
        for (RankDto rankDto : list){
            rankDto.setPraiseNum(ListUtils.isEmpty(praiseMap.get(rankDto.getWxUserId())) ? 0 : praiseMap.get(rankDto.getWxUserId()).size());
            rankDto.setIsPraise(map.getOrDefault(rankDto.getWxUserId(), Boolean.FALSE) ? 1 : 0);
        }
    }

    @Override
    public PageBeanNew<ListPraiseUserResponseVO> listPraiseUser(String wxGroupId, String wxUserId, PageParam pageParam){
        Map<String, Object> paramMap = new HashMap<>();
        PageBeanNew<WeixinClockPraise> pageBeanNew = weixinClockPraiseDao.listPageNew(pageParam, paramMap, "listByWxUserId");
        List<WeixinClockPraise> weixinClockPraiseList = pageBeanNew.getRecordList();
        if (ListUtils.isEmpty(weixinClockPraiseList)){
            return new PageBeanNew<>(pageParam.getPageNum(), pageParam.getNumPerPage(), 0, new ArrayList<>());
        }
        List<Long> wechatUserIds = weixinClockPraiseList.stream().map(WeixinClockPraise::getPraiseUserId).distinct().collect(Collectors.toList());
        Map<Long, WechatUser> wechatUserMap = readerConsr.getUserList(wechatUserIds);
        List<ListPraiseUserResponseVO> vos = ListPraiseUserResponseVO.valueFromPraiseUser(weixinClockPraiseList, wechatUserMap);
        return new PageBeanNew<>(pageParam.getPageNum(), pageParam.getNumPerPage(), pageBeanNew.getTotalCount(), vos);
    }
}
