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

import com.google.common.collect.Maps;
import com.pcloud.book.applet.biz.AppletGroupSearchRecordBiz;
import com.pcloud.book.applet.biz.AppletNewsBiz;
import com.pcloud.book.applet.biz.AppletUserBookcaseBiz;
import com.pcloud.book.applet.contants.AppletConstants;
import com.pcloud.book.applet.dao.AppletGroupSearchRecordDao;
import com.pcloud.book.applet.dao.AppletGroupStatementDao;
import com.pcloud.book.applet.dto.AppletGroupManageDTO;
import com.pcloud.book.applet.dto.AppletGroupSearchRecordDTO;
import com.pcloud.book.applet.dto.AppletGroupStatementDTO;
import com.pcloud.book.applet.dto.AppletUserBookcaseDTO;
import com.pcloud.book.applet.entity.AppletGroupSearchRecord;
import com.pcloud.book.applet.entity.AppletGroupStatement;
import com.pcloud.book.book.dao.BookAdviserDao;
import com.pcloud.book.book.dto.BookAdviserDto;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.book.group.biz.BookGroupClassifyBiz;
import com.pcloud.book.group.biz.GroupQrcodeBiz;
import com.pcloud.book.group.dao.BookClassifyBuyRecordDao;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dao.BookQrcodeUserDao;
import com.pcloud.book.group.dao.GroupQrcodeDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.BookServeDTO;
import com.pcloud.book.group.dto.GroupQrcodeDTO;
import com.pcloud.book.group.enums.JoinGroupTypeEnum;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.dto.RightsSettingDto;
import com.pcloud.book.rightsSetting.entity.BaseTempletClassify;
import com.pcloud.book.skill.biz.PcloudGroupActivityBiz;
import com.pcloud.book.skill.dao.PcloudGroupActivityDao;
import com.pcloud.book.applet.dto.GroupActivity4AppletDTO;
import com.pcloud.book.util.common.YesOrNoEnums;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtilParent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (AppletGroupSearchRecord)表服务实现类
 *
 * @author zyq
 * @since 2020-04-01 17:34:47
 */
@Service("appletGroupSearchRecordBiz")
public class AppletGroupSearchRecordBizImpl implements AppletGroupSearchRecordBiz {

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

    @Autowired
    private AppletGroupSearchRecordDao appletGroupSearchRecordDao;
    @Autowired
    private BookGroupClassifyBiz bookGroupClassifyBiz;

    @Resource
    private PcloudGroupActivityDao pcloudGroupActivityDao;

    @Autowired
    private RightsSettingBiz rightsSettingBiz;
    @Autowired
    private BookGroupDao bookGroupDao;

    @Autowired
    private BookAdviserDao bookAdviserDao;

    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private GroupQrcodeDao groupQrcodeDao;
    @Autowired
    private AppletGroupStatementDao appletGroupStatementDao;
    @Autowired
    private AppletUserBookcaseBiz appletUserBookcaseBiz;
    @Autowired
    private PcloudGroupActivityBiz pcloudGroupActivityBiz;
    @Autowired
    private BookQrcodeUserDao bookQrcodeUserDao;
    @Autowired
    private BookGroupBiz bookGroupBiz;
    @Autowired
    private BookClassifyBuyRecordDao bookClassifyBuyRecordDao;
    @Autowired
    private GroupQrcodeBiz groupQrcodeBiz;
    @Autowired
    private AppletNewsBiz appletNewsBiz;

    @Override
    @ParamLog("通过ID查询单条数据")
    public AppletGroupSearchRecord getById(Long id) {
        return appletGroupSearchRecordDao.getById(id);
    }

    @Override
    @ParamLog("查询多条数据")
    public PageBeanNew getList(Long wechatUserId, Integer isMore, Integer currentPage, Integer numPerPage, Long agentId) {
        Map<String, Object> map = new HashMap<>();
        map.put("wechatUserId", wechatUserId);
        map.put("agentId", agentId);
        PageBeanNew pageBeanNew = appletGroupSearchRecordDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getList");
        List<AppletGroupSearchRecordDTO> recordList = pageBeanNew.getRecordList();
        if (ListUtils.isEmpty(recordList)) {
            return pageBeanNew;
        }
        // 填充分类信息
        for (AppletGroupSearchRecordDTO dto : recordList) {
            if (isMore == 1) {
                dto.setClassifyCount(bookGroupClassifyBiz.getClassifyCount(dto.getBookGroupId()));
            } else {
                dto.setClassify4WechatVOList(bookGroupClassifyBiz.listClassify4Wechat(dto.getBookGroupId(), dto.getWechatUserId()));
            }
            // 权益、资源、社群
            fillRightsSettingAndResourceCount(recordList);
        }
        return pageBeanNew;
    }

    private void fillRightsSettingAndResourceCount(List<AppletGroupSearchRecordDTO> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        for (AppletGroupSearchRecordDTO bookcaseDTO : recordList) {
            //权益
            if (JoinGroupTypeEnum.XIAORUI.getCode().equals(bookcaseDTO.getJoinGroupType())) {
                RightsSettingDto rightsSettingDto = rightsSettingBiz.getRightsSettingByBookId4AppletHome(bookcaseDTO.getBookId(), bookcaseDTO.getAdviserId(), bookcaseDTO.getChannelId());
                if (null == rightsSettingDto) {
                    continue;
                }
                bookcaseDTO.setRightsSettingCount(rightsSettingDto.getCount());
            }
            //资源数量
            List<BookServeDTO> serveDTOList = bookGroupBiz.getBookAndBookGroupServeIds(bookcaseDTO.getAdviserId(), bookcaseDTO.getBookId(), bookcaseDTO.getChannelId());
            bookGroupBiz.removeCanNotBuy(serveDTOList);
            bookcaseDTO.setResourceCount(serveDTOList.size());
        }
    }

    @Override
    @ParamLog("新增")
    public Long insert(AppletGroupSearchRecord appletGroupSearchRecord) {
        if (!NumberUtil.isNumber(appletGroupSearchRecord.getBookId()) || !NumberUtil.isNumber(appletGroupSearchRecord.getChannelId()) || !NumberUtil.isNumber(appletGroupSearchRecord.getAdviserId())) {
            throw BizException.PARAM_DELETION;
        }
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOByBookId(appletGroupSearchRecord.getBookId(), appletGroupSearchRecord.getChannelId(), appletGroupSearchRecord.getAdviserId());
        // 判断是否包含社群标识
        if (bookGroupDTO != null && bookGroupDTO.getId() != null && bookGroupDTO.getId() > 0 && (
                (bookGroupDTO.getJoinGroupType() != null && bookGroupDTO.getJoinGroupType() == 1) || (bookGroupDTO.getRelatedBookGroupId() != null && bookGroupDTO.getRelatedBookGroupId() > 0))
        ) {
            appletGroupSearchRecord.setBookGroupId(bookGroupDTO.getId());
            appletGroupSearchRecordDao.insert(appletGroupSearchRecord);
            return appletGroupSearchRecord.getId();
        }
        return 0L;
    }

    @Override
    @ParamLog("修改")
    public void update(AppletGroupSearchRecord appletGroupSearchRecord) {
        if (appletGroupSearchRecord == null || !NumberUtil.isNumber(appletGroupSearchRecord.getId())) {
            throw BizException.PARAM_DELETION;
        }
        appletGroupSearchRecordDao.update(appletGroupSearchRecord);
    }

    @Override
    @ParamLog("删除")
    public void deleteById(Long id) {
        appletGroupSearchRecordDao.deleteById(id);
    }

    @Override
    @ParamLog("删除")
    public void deleteByIds(List<Long> ids) {
        if (ListUtils.isEmpty(ids)) {
            throw BizException.PARAM_DELETION;
        }
        appletGroupSearchRecordDao.deleteByIds(ids);
    }

    @Override
    public List<GroupActivity4AppletDTO> getTishBookSchoolList(Long wechatUserId, Long bookGroupId, Long officialAccountsId) {
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
        List<GroupActivity4AppletDTO> tishBookSchoolList = new ArrayList<>();
        //本书自带社群
        if (JoinGroupTypeEnum.GROUP_QRCODE.getCode().equals(bookGroupDTO.getJoinGroupType())) {
            List<GroupQrcodeDTO> groupQrcodeDTOS = groupQrcodeDao.listClassifyLatestGroupByBookGroup(bookGroupId);
            if (!ListUtils.isEmpty(groupQrcodeDTOS)) {
                for (GroupQrcodeDTO qrcodeDTO : groupQrcodeDTOS) {
                    GroupActivity4AppletDTO appletDTO = new GroupActivity4AppletDTO();
                    BeanUtils.copyProperties(qrcodeDTO, appletDTO);
                    appletDTO.setName(qrcodeDTO.getGroupName());
                    appletDTO.setDesc(qrcodeDTO.getClassifyIntroduce());
                    appletDTO.setBookGroupId(bookGroupId);
                    appletDTO.setBookGroupQrcodeId(qrcodeDTO.getId());
                    tishBookSchoolList.add(appletDTO);
                }
            }
        }
        //本书关联社群
        if (null != bookGroupDTO.getRelatedBookGroupId()){
            Long relatedGroupId = bookGroupDTO.getRelatedBookGroupId();
            List<GroupQrcodeDTO> qrcodeDTOS = groupQrcodeDao.listClassifyLatestGroupByBookGroup(relatedGroupId);
            if (!ListUtils.isEmpty(qrcodeDTOS)) {
                for (GroupQrcodeDTO qrcodeDTO : qrcodeDTOS) {
                    GroupActivity4AppletDTO appletDTO = new GroupActivity4AppletDTO();
                    BeanUtils.copyProperties(qrcodeDTO, appletDTO);
                    appletDTO.setName(qrcodeDTO.getGroupName());
                    appletDTO.setDesc(qrcodeDTO.getClassifyIntroduce());
                    appletDTO.setBookGroupId(bookGroupId);
                    appletDTO.setRelatedBookGroupId(relatedGroupId);
                    appletDTO.setBookGroupQrcodeId(qrcodeDTO.getId());
                    tishBookSchoolList.add(appletDTO);
                }
            }
        }

        // 本书相关社群不足三个的，应该从平台端技能配置相关分类里拼社群
        if (tishBookSchoolList.size()<3){
            int num = 3 - tishBookSchoolList.size();
            // 通过bookGroupId反查社群
            BookAdviserDto bookAdviser = bookAdviserDao.getByBookGroupId(bookGroupId);
            BaseTempletClassify baseTempletClassify = new BaseTempletClassify();
            baseTempletClassify.setFirstClassify(bookAdviser.getTempletId());
            baseTempletClassify.setSecondClassify(bookAdviser.getSecondTempletId());
            baseTempletClassify.setThirdClassify(bookAdviser.getThirdTempletId());
            baseTempletClassify.setGradeLabelId(bookAdviser.getGraLabelId());
            baseTempletClassify.setSubjectLabelId(bookAdviser.getSubLabelId());
            // 部分分类需要忽略二级分类
            rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);
            Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
            Map<String, Object> paraMap = Maps.newHashMap();
            paraMap.put("firstClassify", baseTempletClassify.getFirstClassify());
            paraMap.put("secondClassify", baseTempletClassify.getSecondClassify());
            paraMap.put("thirdClassify", baseTempletClassify.getThirdClassify());
            paraMap.put("gradeLabelId", baseTempletClassify.getGradeLabelId());
            paraMap.put("subjectLabelId", baseTempletClassify.getSubjectLabelId());
            paraMap.put("agentId", agentId);
            List<Long> classifyIds = pcloudGroupActivityDao.getGroupClassifyIds(paraMap);
            List<Long> collect = tishBookSchoolList.stream().map(GroupActivity4AppletDTO::getClassifyId).distinct().collect(Collectors.toList());
            classifyIds.removeAll(collect);
            if (!ListUtils.isEmpty(classifyIds)){
                List<GroupQrcodeDTO> qrcodeDTOS = groupQrcodeDao.getGroupQrcodeByClassifyIds(classifyIds);
                if (!ListUtils.isEmpty(qrcodeDTOS)) {
                    for (GroupQrcodeDTO qrcodeDTO : qrcodeDTOS) {
                        GroupActivity4AppletDTO appletDTO = new GroupActivity4AppletDTO();
                        BeanUtils.copyProperties(qrcodeDTO, appletDTO);
                        appletDTO.setName(qrcodeDTO.getGroupName());
                        appletDTO.setDesc(qrcodeDTO.getClassifyIntroduce());
                        appletDTO.setBookGroupQrcodeId(qrcodeDTO.getId());
                        tishBookSchoolList.add(appletDTO);
                    }
                }
            }
        }

        if (ListUtils.isEmpty(tishBookSchoolList)) {
            return new ArrayList<>();
        }
        for (GroupActivity4AppletDTO groupActivity4AppletDTO : tishBookSchoolList) {
            String filterStr = StringUtilParent.replaceHtml(groupActivity4AppletDTO.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            groupActivity4AppletDTO.setCutDesc(subStr);
            groupActivity4AppletDTO.setStatus(0);
            // 付费群 查询用户是否已经购买过该群分类
            if (groupActivity4AppletDTO.getPrice().compareTo(BigDecimal.ZERO) > 0) {
                if (bookClassifyBuyRecordDao.checkUserBuy(wechatUserId, groupActivity4AppletDTO.getClassifyId())) {
                    groupActivity4AppletDTO.setStatus(1);
                }
            }
            if(null != groupActivity4AppletDTO.getGroupType() && groupActivity4AppletDTO.getGroupType().intValue() == YesOrNoEnums.YES.getValue()){
                //第三方群自主填充
                rightsSettingBiz.fillThirdGroupHeadList(groupActivity4AppletDTO);
            } else {
                //头像列表从缓存里取
                List<String> headUrlList = this.getHeadUrlList(groupActivity4AppletDTO.getUserNumber(), groupActivity4AppletDTO.getBookGroupQrcodeId());
                groupActivity4AppletDTO.setHeadUrlList(headUrlList);
                List<AppletGroupStatementDTO> statementDTOS = this.getStatementList(groupActivity4AppletDTO.getUserNumber(), headUrlList, groupActivity4AppletDTO.getBookGroupQrcodeId());
                groupActivity4AppletDTO.setStatementDTOList(statementDTOS);
            }
        }
        return tishBookSchoolList;
    }

    @Override
    public List<String> getHeadUrlList(Integer userNum, Long groupQrcodeId) {
        List<String> headUrlList = JedisClusterUtils.hgetJson2List(AppletConstants.GROUP_HEAD_URL_REDIS, groupQrcodeId.toString(), String.class);
        if (ListUtils.isEmpty(headUrlList) || (headUrlList.size() < 9 && !userNum.equals(headUrlList.size()))) {
            headUrlList = readerConsr.getRandomHeadUrlList(userNum > 9 ? 9 : userNum);
            JedisClusterUtils.hset2Json(AppletConstants.GROUP_HEAD_URL_REDIS, groupQrcodeId.toString(), headUrlList);
            JedisClusterUtils.expire(AppletConstants.GROUP_HEAD_URL_REDIS, 3600);
        }
        return headUrlList;
    }

    @Override
    public List<AppletGroupStatementDTO> getStatementList(Integer userNum, List<String> headUrlList, Long groupQrcodeId) {
        if (userNum <= 0) {
            return new ArrayList<>();
        }
        List<AppletGroupStatementDTO> statementDTOS = JedisClusterUtils.hgetJson2List(AppletConstants.GROUP_STATEMENT_REDIS, groupQrcodeId.toString(), AppletGroupStatementDTO.class);
        if (ListUtils.isEmpty(statementDTOS) || (statementDTOS.size() < 9 && !userNum.equals(statementDTOS.size()))) {
            statementDTOS = new ArrayList<>();
            userNum = userNum > 50 ? 50 : userNum;//最多50条
            List<String> headUrls = new ArrayList<>();
            headUrls.addAll(headUrlList);
            if (headUrlList.size() < userNum) {
                headUrls.addAll(readerConsr.getRandomHeadUrlList(userNum - headUrlList.size()));
            }
            List<AppletGroupStatement> statementList = appletGroupStatementDao.getRandom(userNum);
            for (int i = 0; i < userNum; i++) {
                AppletGroupStatementDTO statementDTO = new AppletGroupStatementDTO();
                statementDTO.setHeadUrl(headUrls.get(i));
                AppletGroupStatement statement = statementList.get(i);
                statementDTO.setStatement(statement.getStatement());
                statementDTO.setType(statement.getType());
                statementDTO.setDuration(statement.getDuration());
                statementDTOS.add(statementDTO);
            }
            JedisClusterUtils.hset2Json(AppletConstants.GROUP_STATEMENT_REDIS, groupQrcodeId.toString(), statementDTOS);
            JedisClusterUtils.expire(AppletConstants.GROUP_STATEMENT_REDIS, 3600);
        }
        return statementDTOS;
    }

    @Override
    public List<Long> getRecordIdListByUser(Long wechatUserId) {
        return appletGroupSearchRecordDao.getRecordIdListByUser(wechatUserId);
    }

    @Override
    public PageBeanNew<AppletGroupManageDTO> getGroupList4AppletHome(Long wechatUserId, Integer currentPage, Integer numPerPage, Long officialAccountsId) {
        //用户最近读的书
        PageBeanNew<AppletUserBookcaseDTO> bookcaseDTOPageBeanNew = appletUserBookcaseBiz.listByWechatUserId(wechatUserId, currentPage, 1);
        if (null == bookcaseDTOPageBeanNew || ListUtils.isEmpty(bookcaseDTOPageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        AppletUserBookcaseDTO bookcaseDTO = bookcaseDTOPageBeanNew.getRecordList().get(0);
        if (null == bookcaseDTO) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
        PageBeanNew<AppletGroupManageDTO> pageBeanNew = pcloudGroupActivityBiz.getGroupListByBookTemplet(wechatUserId, bookcaseDTO.getTempletId(), bookcaseDTO.getSecondTempletId(),
                bookcaseDTO.getGradeLabelId(), bookcaseDTO.getSubjectLabelId(), currentPage, numPerPage, agentId, bookcaseDTO.getThirdTempletId());
        return pageBeanNew;
    }

}