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

import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.applet.biz.AppletUserBookcaseBiz;
import com.pcloud.book.applet.dao.AppletUserBookcaseDao;
import com.pcloud.book.applet.dto.AppletUserBookcaseDTO;
import com.pcloud.book.applet.entity.AppletUserBookcase;
import com.pcloud.book.applet.entity.AppletUserClickRecord;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.channelcenter.wechat.dto.BookServeParamVO;
import com.pcloud.channelcenter.wechat.vo.BookServeVO;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
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.usercenter.party.adviser.dto.AdviserBaseInfoDto;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 小程序用户书架
 */
@Component
public class AppletUserBookcaseBizImpl implements AppletUserBookcaseBiz {

    @Autowired
    private AppletUserBookcaseDao appletUserBookcaseDao;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;

    @Override
    public void addUserBook(AppletUserBookcase appletUserBookcase) {
        appletUserBookcaseDao.insert(appletUserBookcase);
        Long wechatUserId = appletUserBookcase.getWechatUserId();
        String key = "BOOK:APPLET:listByWechatUserId"+wechatUserId;
        String countKey = "BOOK:APPLET:listByWechatUserId-count"+wechatUserId;
        JedisClusterUtils.del(key);
        JedisClusterUtils.del(countKey);
    }

    @Override
    public PageBeanNew<AppletUserBookcaseDTO> listByWechatUserId(Long wechatUserId, Integer currentPage, Integer numPerPage) {
        String key = "BOOK:APPLET:listByWechatUserId"+wechatUserId;
        String field = currentPage+"-"+numPerPage;
        String countKey = "BOOK:APPLET:listByWechatUserId-count"+wechatUserId;
        List<AppletUserBookcaseDTO> bookcaseDTOS = JedisClusterUtils.hgetJson2List(key,field,AppletUserBookcaseDTO.class);
        Integer count =0;
        String countStr = JedisClusterUtils.get(countKey);
        if (!StringUtil.isEmpty(countStr)){
            count = Integer.valueOf(countStr);
        }
        if (!ListUtils.isEmpty(bookcaseDTOS) && count>0){
            return new PageBeanNew<>(currentPage,numPerPage,count,bookcaseDTOS);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("wechatUserId",wechatUserId);
        PageBeanNew<AppletUserBookcaseDTO> pageBeanNew = appletUserBookcaseDao.listPageNew(
                new PageParam(currentPage,numPerPage),map,"listByWechatUserId");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())){
            return new PageBeanNew<>(currentPage,numPerPage,0,new ArrayList<>());
        }
        fillTempletName(pageBeanNew.getRecordList());
        JedisClusterUtils.hset2Json(key,field,pageBeanNew.getRecordList());
        JedisClusterUtils.set(countKey,String.valueOf(pageBeanNew.getTotalCount()));
        return pageBeanNew;
    }

    @Override
    public void addUserClickRecord(AppletUserClickRecord appletUserClickRecord) {
        appletUserBookcaseDao.insertClickRecord(appletUserClickRecord);
    }

    @Override
    public Map<String, Object> getUserClickStatistic(Long wechatUserId, Long bookId, Long channelId, Long adviserId) {
        //书刊下所有资源
        BookServeParamVO serveParamVO = new BookServeParamVO();
        serveParamVO.setBookId(bookId);
        serveParamVO.setAdviserId(adviserId);
        serveParamVO.setChannelId(channelId);
        List<BookServeVO> serveVOList = qrcodeSceneConsr.listBookServeIds(serveParamVO);
        if (ListUtils.isEmpty(serveVOList)){
            return new HashMap<>();
        }
        Integer clickCount = 0;
        String startDate = DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATEONLY);
        List<Long> appIds = serveVOList.stream().filter(s->s.getTypeCode().equalsIgnoreCase("APP")).
                map(BookServeVO::getServeId).distinct().collect(Collectors.toList());
        List<Long> productIds = serveVOList.stream().filter(s->s.getTypeCode().equalsIgnoreCase("PRODUCT")).
                map(BookServeVO::getServeId).distinct().collect(Collectors.toList());
        if (!ListUtils.isEmpty(appIds)){
            Integer appCount = appletUserBookcaseDao.getUserClickServerCount(wechatUserId,bookId,channelId,adviserId,appIds,"APP");
            if (appCount>0){
                clickCount = clickCount+appCount;
                startDate = appletUserBookcaseDao.getMinClickTime(wechatUserId,bookId,channelId,adviserId,appIds,"APP");
            }
        }
        if (!ListUtils.isEmpty(productIds)){
            Integer productCount = appletUserBookcaseDao.getUserClickServerCount(wechatUserId,bookId,channelId,adviserId,productIds,"PRODUCT");
            if (productCount>0){
                clickCount = clickCount+productCount;
                String dateStr = appletUserBookcaseDao.getMinClickTime(wechatUserId,bookId,channelId,adviserId,productIds,"PRODUCT");
                if (!StringUtil.isEmpty(dateStr) && DateUtils.getDateByStr(dateStr).before(DateUtils.getDateByStr(startDate))){
                    startDate = dateStr;
                }
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("startDate", startDate);
        map.put("clickCount", clickCount);
        return map;
    }

    private void fillTempletName(List<AppletUserBookcaseDTO> recordList) {
        List<Long> templetIds = new ArrayList<>();
        recordList.forEach(dto -> {
            if (Objects.nonNull(dto.getTempletId())) {
                templetIds.add(dto.getTempletId());
            }
            if (Objects.nonNull(dto.getSecondTempletId())) {
                templetIds.add(dto.getSecondTempletId());
            }
        });
        Map<Long, AssistTempletDTO> assistTempletDTOMap = assistTempletConsr.mapByIds(templetIds);
        for (AppletUserBookcaseDTO bookcaseDTO:recordList){
            Long secondTempletId = bookcaseDTO.getSecondTempletId();
            Long templetId = bookcaseDTO.getTempletId();
            if (secondTempletId!=null&&assistTempletDTOMap!=null) {
                AssistTempletDTO templetDTO = assistTempletDTOMap.get(secondTempletId);
                bookcaseDTO.setSecondTempletName(Optional.ofNullable(templetDTO).map(AssistTempletDTO::getTempletName).orElse(null));
            }
            if (templetId!=null && assistTempletDTOMap!=null) {
                AssistTempletDTO templetDTO = assistTempletDTOMap.get(templetId);
                bookcaseDTO.setTempletName(Optional.ofNullable(templetDTO).map(AssistTempletDTO::getTempletName).orElse(null));
            }
        }
    }


}
