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

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.dao.BookLabelDao;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.book.entity.BookLabel;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.consumer.label.LabelConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.GroupQrcodeBiz;
import com.pcloud.book.group.vo.GroupQrcodeBaseInfoVO;
import com.pcloud.book.reading.biz.ReadingActivityBiz;
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.rightsSetting.entity.RightsSettingTitle;
import com.pcloud.book.rightsSetting.enums.RightsNowItemType;
import com.pcloud.book.rightsSetting.mapper.RightsSettingTitleMapper;
import com.pcloud.book.skill.biz.PcloudGroupActivityBiz;
import com.pcloud.book.skill.dao.PcloudGroupActivityDao;
import com.pcloud.book.skill.dao.PcloudSkillDao;
import com.pcloud.book.skill.dto.GroupActivity4AppletDTO;
import com.pcloud.book.skill.entity.PcloudGroupActivity;
import com.pcloud.book.skill.entity.PcloudSkill;
import com.pcloud.book.skill.enums.SkillTypeEnum;
import com.pcloud.book.skill.facade.request.SaveGroupActivityRequestVO;
import com.pcloud.book.skill.facade.request.UpdateGroupActivityRequestVO;
import com.pcloud.book.skill.facade.response.QueryGroupActivityResponseVO;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtilParent;
import com.sdk.wxgroup.RobotProcessTypeEnum;
import com.sdk.wxgroup.SendGroupInviteVO;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.WxGroupSDK;


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.UUID;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class PcloudGroupActivityBizImpl implements PcloudGroupActivityBiz {

    private static final String GROUP_HEAD_URL_REDIS="BOOK:APPLET:pcloudGroupActivityBizImpl_groupHeadUrl";

    @Resource
    private PcloudSkillDao pcloudSkillDao;
    @Resource
    private PcloudGroupActivityDao pcloudGroupActivityDao;
    @Resource
    private GroupQrcodeBiz groupQrcodeBiz;
    @Resource
    private ReadingActivityBiz readingActivityBiz;
    @Resource
    private LabelConsr labelConsr;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private RightsSettingBiz rightsSettingBiz;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private BookLabelDao bookLabelDao;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Autowired
    private BookBiz bookBiz;
    @Autowired
    private RightsSettingTitleMapper rightsSettingTitleMapper;

    @ParamLog("保存共读活动")
    @Override
    public void saveGroupActivity(SaveGroupActivityRequestVO vo) {
        vo.checkParam();
        PcloudGroupActivity entity = vo.getEntity();
        Date now = new Date();
        entity.setCreateUser(vo.getUserId());
        entity.setCreateTime(now);
        entity.setUpdateUser(vo.getUserId());
        entity.setUpdateTime(now);
        entity.setIsDelete(0);
        rightsSettingBiz.setClassifyAndLabel(entity);
        pcloudGroupActivityDao.insert(entity);

    }

    @Override
    public void updateGroupActivity(UpdateGroupActivityRequestVO vo) {
        vo.checkParam();
        PcloudGroupActivity activity = pcloudGroupActivityDao.getById(vo.getId());
        if (null == activity) {
            throw new BookBizException(BookBizException.ID_NOT_EXIST, "共读活动不存在");
        }
        PcloudGroupActivity entity = vo.getEntity();
        Date now = new Date();
        entity.setUpdateUser(vo.getUserId());
        entity.setUpdateTime(now);
        rightsSettingBiz.setClassifyAndLabel(entity);
        pcloudGroupActivityDao.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void deleteGroupActivity(Long id, Long partyId) {
        if (Objects.isNull(id)) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "该共读活动不存在！");
        }
        PcloudSkill byRelId = pcloudSkillDao.getByRelId(id.intValue(), SkillTypeEnum.READING.value);
        if (Objects.nonNull(byRelId)) {
            throw new BookBizException(BookBizException.PARAM_IS_EXIST, "该共读活动已经关联技能，无法删除！");
        }
        pcloudGroupActivityDao.deleteById(id);
    }

    @Override
    @ParamLog("[processGroup]")
    public void processGroup(String wxId, String robotWxId, Long id) {
        PcloudGroupActivity byId = pcloudGroupActivityDao.getById(id);
        if (Objects.isNull(byId)) {
            log.error("[processGroup] error 共读不存在");
            return;
        }
        Integer count= 1;
        String messageGroup =  UUID.randomUUID().toString();
        Integer index = 0;
        if (0 == byId.getJoinType()) {
            GroupQrcodeBaseInfoVO groupQrcode = groupQrcodeBiz.getBaseById(byId.getBookGroupQrcodeId());
            if (Objects.isNull(groupQrcode)) {
                log.error("[processGroup] error 共读对应社群不存在");
                return;
            }
            SendGroupInviteVO vo = new SendGroupInviteVO();
            vo.setWxId(wxId);
            vo.setAltId(robotWxId);
            vo.setIp(readingActivityBiz.getIP(robotWxId));
            vo.setWxGroupId(groupQrcode.getWeixinGroupId());
            vo.setCounts(count);
            vo.setMessageGroupId(messageGroup);
            vo.setIndex(index);
            vo.setRobotProcessType(RobotProcessTypeEnum.SKILL_REPLY);
            wechatGroupConsr.sendMessage(JSON.toJSONString(vo));
            log.info("[processGroup] sendGroupInvite:{}", vo);
        }
        if (1 == byId.getJoinType()) {
            SendPicMessageVO vo = new SendPicMessageVO();
            vo.setPicUrl(byId.getGroupPic());
            vo.setWxGroupId(wxId);
            vo.setAltId(robotWxId);
            vo.setIp(readingActivityBiz.getIP(robotWxId));
            vo.setCounts(count);
            vo.setMessageGroupId(messageGroup);
            vo.setIndex(index);
            vo.setRobotProcessType(RobotProcessTypeEnum.SKILL_REPLY);
            wechatGroupConsr.sendMessage(JSON.toJSONString(vo));
        }
    }

    @Override
    public PageBeanNew<QueryGroupActivityResponseVO> queryGroupActivity(String name, Long proLabelId, Long purLabelId, Long depLabelId, Integer joinType,Long firstClassify,
                                                                        Long secondClassify,
                                                                        Long gradeLabelId,
                                                                        Long subjectLabelId, Integer numPerPage, Integer currentPage) {
        PageParam pageParam = new PageParam(currentPage, numPerPage);
        BaseTempletClassify baseTempletClassify =new BaseTempletClassify();
        baseTempletClassify.setFirstClassify(firstClassify);
        baseTempletClassify.setSecondClassify(secondClassify);
        baseTempletClassify.setSubjectLabelId(subjectLabelId);
        baseTempletClassify.setGradeLabelId(gradeLabelId);
        if (null != baseTempletClassify.getFirstClassify()){
            rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);
        }
        Map<String, Object> paraMap = Maps.newHashMap();
        paraMap.put("name", name);
        paraMap.put("proLabelId", proLabelId);
        paraMap.put("purLabelId", purLabelId);
        paraMap.put("depLabelId", depLabelId);
        paraMap.put("joinType", joinType);
        paraMap.put("firstClassify", baseTempletClassify.getFirstClassify());
        paraMap.put("secondClassify", baseTempletClassify.getSecondClassify());
        paraMap.put("gradeLabelId", baseTempletClassify.getGradeLabelId());
        paraMap.put("subjectLabelId", baseTempletClassify.getSubjectLabelId());
        PageBeanNew<QueryGroupActivityResponseVO> queryGroupActivity = pcloudGroupActivityDao.listPageNew(pageParam, paraMap, "queryGroupActivity");
        if (null == queryGroupActivity || CollectionUtils.isEmpty(queryGroupActivity.getRecordList())) {
            return queryGroupActivity;
        }
        // 组装标签名称
        List<Long> labelId = Lists.newArrayList();
        for (QueryGroupActivityResponseVO responseVO : queryGroupActivity.getRecordList()) {
            labelId.add(responseVO.getProLabelId());
            labelId.add(responseVO.getPurLabelId());
            labelId.add(responseVO.getDepLabelId());
        }
        Map<Long, String> labelName = labelConsr.getLabelName(labelId);
        for (QueryGroupActivityResponseVO responseVO : queryGroupActivity.getRecordList()) {
            responseVO.setPurLabelName(labelName.get(responseVO.getPurLabelId()));
            responseVO.setProLabelName(labelName.get(responseVO.getProLabelId()));
            responseVO.setDepLabelName(labelName.get(responseVO.getDepLabelId()));
        }
        //设置分类名称
        setLabelContent(queryGroupActivity.getRecordList());
        // 截取字符串
        for(QueryGroupActivityResponseVO vo : queryGroupActivity.getRecordList()){
            String filterStr = StringUtilParent.replaceHtml(vo.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            vo.setCutDesc(subStr);
        }

        return queryGroupActivity;
    }
    private void setLabelContent(List<QueryGroupActivityResponseVO> rightsSettingDtos) {
        log.info("权益设置标签具体内容");
        if (ListUtils.isEmpty(rightsSettingDtos)){
            return;
        }
        List<Long> firstClassifyIds = new ArrayList<>();
        List<Long> secondClassifyIds = new ArrayList<>();
        List<Long> classifyIds = new ArrayList<>();
        List<Long> gradeLabelIds = new ArrayList<>();
        List<Long> subjectLabelIds = new ArrayList<>();
        List<Long> labelIds = new ArrayList<>();
        for (QueryGroupActivityResponseVO queryGroupActivityResponseVO:rightsSettingDtos) {
            firstClassifyIds.add(queryGroupActivityResponseVO.getFirstClassify());
            secondClassifyIds.add(queryGroupActivityResponseVO.getSecondClassify());
            gradeLabelIds.add(queryGroupActivityResponseVO.getGradeLabelId());
            subjectLabelIds.add(queryGroupActivityResponseVO.getSubjectLabelId());
        }
        if (!ListUtils.isEmpty(firstClassifyIds)){
            classifyIds.addAll(firstClassifyIds);
        }
        if (!ListUtils.isEmpty(secondClassifyIds)){
            classifyIds.addAll(secondClassifyIds);
        }
        if (!ListUtils.isEmpty(gradeLabelIds)){
            labelIds.addAll(gradeLabelIds);
        }
        if (!ListUtils.isEmpty(subjectLabelIds)){
            labelIds.addAll(subjectLabelIds);
        }
        Map<Long, AssistTempletDTO> classifyMap = new HashMap<>();
        Map<Long, BookLabel>  labelMap= new HashMap<>();
        if (!ListUtils.isEmpty(classifyIds)){
            classifyMap = assistTempletConsr.mapByIds4Classify(classifyIds);
        }
        if (!ListUtils.isEmpty(labelIds)){
            labelMap = bookLabelDao.getMapByIds(labelIds);
        }
        for (QueryGroupActivityResponseVO rightsSettingDto : rightsSettingDtos){
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getFirstClassify())){
                rightsSettingDto.setFirstClassifyName(classifyMap.get(rightsSettingDto.getFirstClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getSecondClassify())){
                rightsSettingDto.setSecondClassifyName(classifyMap.get(rightsSettingDto.getSecondClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getGradeLabelId())){
                rightsSettingDto.setGradeLabelName(labelMap.get(rightsSettingDto.getGradeLabelId()).getName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getSubjectLabelId())){
                rightsSettingDto.setSubjectLabelName(labelMap.get(rightsSettingDto.getSubjectLabelId()).getName());
            }
        }
    }

    @Override
    public GroupActivity4AppletDTO getGroupActivity4Applet(Long rightSettingId, Long adviserId, Long bookId, Long channelId) {
        BookDto adviserBook = bookBiz.getAdviserBook(bookId, adviserId, channelId);
        BookDto dto = Optional.ofNullable(adviserBook).orElseThrow(() -> new BookBizException(BookBizException.ID_NOT_EXIST, "未找到相关书刊"));
        // 处理分类和标签
        BaseTempletClassify baseTempletClassify = new BaseTempletClassify();
        baseTempletClassify.setFirstClassify(dto.getTempletId());
        baseTempletClassify.setSecondClassify(dto.getSecondTempletId());
        baseTempletClassify.setGradeLabelId(dto.getGraLabelId());
        baseTempletClassify.setSubjectLabelId(dto.getSubLabelId());
        rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);

        GroupActivity4AppletDTO groupActivity4AppletDTO = pcloudGroupActivityDao.getGroupActivity4Applet(baseTempletClassify.getFirstClassify(),baseTempletClassify.getSecondClassify(),baseTempletClassify.getGradeLabelId(),baseTempletClassify.getSubjectLabelId());
        if(groupActivity4AppletDTO == null){
            return new GroupActivity4AppletDTO();
        }
        // 是否开启社群服务开关
        RightsSettingTitle right = rightsSettingTitleMapper.getByRightSettingIdAndType(rightSettingId, RightsNowItemType.GROUP_SERVICE.value);
        groupActivity4AppletDTO.setOpenStatus(Objects.isNull(right) ? false : right.getOpenState());
        groupActivity4AppletDTO.setRightsSettingTitle(right.getRightsSettingTitle());
        groupActivity4AppletDTO.setRightsSettingDesc(right.getRightsSettingDesc());
        String filterStr = StringUtilParent.replaceHtml(groupActivity4AppletDTO.getDesc());
        String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
        groupActivity4AppletDTO.setCutDesc(subStr);
        //头像列表从缓存里取
        List<String> headUrlList = JedisClusterUtils.hgetJson2List(GROUP_HEAD_URL_REDIS,groupActivity4AppletDTO.getGroupActivityId().toString(),String.class);
        //缓存为空或数量不一致，重新获取
        if (ListUtils.isEmpty(headUrlList) ||
            (headUrlList.size()<9 && !groupActivity4AppletDTO.getUserNumber().equals(headUrlList.size()))){
            headUrlList = readerConsr.getRandomHeadUrlList(groupActivity4AppletDTO.getUserNumber()>9 ? 9:groupActivity4AppletDTO.getUserNumber());
            JedisClusterUtils.hset2Json(GROUP_HEAD_URL_REDIS,groupActivity4AppletDTO.getGroupActivityId().toString(),headUrlList);
            JedisClusterUtils.expire(GROUP_HEAD_URL_REDIS,3600);
        }
        groupActivity4AppletDTO.setHeadUrlList(headUrlList);
        return groupActivity4AppletDTO;
    }
}
