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

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.guide.biz.PcloudGuideBiz;
import com.pcloud.book.guide.dto.PcloudGuideDTO;
import com.pcloud.book.guide.dto.PcloudGuideMessageDTO;
import com.pcloud.book.guide.entity.PcloudGuide;
import com.pcloud.book.guide.entity.PcloudGuideMessage;
import com.pcloud.book.guide.entity.PcloudRobotSilence;
import com.pcloud.book.guide.mapper.PcloudGuideMapper;
import com.pcloud.book.guide.mapper.PcloudGuideMessageMapper;
import com.pcloud.book.guide.mapper.PcloudRobotSilenceMapper;
import com.pcloud.book.guide.vo.*;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.utils.BeanUtils;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.pcloud.book.guide.constant.PcloudGuideRedisConstant.PCLOUD_GUIDE_SUFFIX;

@Component("pcloudGuideBiz")
public class PcloudGuideBizImpl implements PcloudGuideBiz {

    @Autowired
    private PcloudGuideMapper pcloudGuideMapper;

    @Autowired
    private PcloudGuideMessageMapper pcloudGuideMessageMapper;

    @Autowired
    private PcloudRobotSilenceMapper pcloudRobotSilenceMapper;

    @Autowired
    private ResourceConsr resourceConsr;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addPcloudGuide(CreatePcloudGuideVO createPcloudGuideVO) {
        //参数校验
        List<PcloudGuideMessageVO> messageVOList = createPcloudGuideVO.getMessageVOList();
        if (ListUtils.isEmpty(messageVOList)) {
            throw new BookBizException(BookBizException.ERROR, "请添加回复内容");
        }
        if (messageVOList.size() > 3) {
            throw new BookBizException(BookBizException.ERROR, "最多添加3条回复内容");
        }

        Integer maxSeqNum = pcloudGuideMapper.getMaxSeqNum(null, null);
        PcloudGuide pcloudGuide = new PcloudGuide();
        pcloudGuide.setType(0);
        pcloudGuide.setRobotWxId(null);
        pcloudGuide.setSeqNum(maxSeqNum + 1);
        pcloudGuide.setTimeSpan(0);
        pcloudGuideMapper.insert(pcloudGuide);
        Integer id = pcloudGuide.getId();
        List<PcloudGuideMessage> list = new ArrayList<>();
        messageVOList.forEach(item -> {
            PcloudGuideMessage pcloudGuideMessage = new PcloudGuideMessage();
            BeanUtils.copyProperties(item, pcloudGuideMessage);
            pcloudGuideMessage.setPcloudGuideId(id);
            list.add(pcloudGuideMessage);
        });
        pcloudGuideMessageMapper.batchInsert(list);
        return id;
    }

    @Override
    public void deletePcloudGuide(Integer pcloudGuideId) {
        pcloudGuideMapper.deleteByPrimaryKey(pcloudGuideId);

        pcloudGuideMessageMapper.deleteByGuideId(pcloudGuideId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePcloudGuide(UpdatePcloudGuideVO updatePcloudGuideVO) {
        PcloudGuide pcloudGuide = pcloudGuideMapper.selectByPrimaryKey(updatePcloudGuideVO.getPcloudGuideId());
        if (null == pcloudGuide) {
            return;
        }
        List<PcloudGuideMessageVO> messageVOList = updatePcloudGuideVO.getMessageVOList();
        if (ListUtils.isEmpty(messageVOList)) {
            throw new BookBizException(BookBizException.ERROR, "请添加回复内容");
        }
        if (messageVOList.size() > 3) {
            throw new BookBizException(BookBizException.ERROR, "最多添加3条回复内容");
        }
        pcloudGuide.setTimeSpan(updatePcloudGuideVO.getTimeSpan());
        pcloudGuideMapper.updateByPrimaryKey(pcloudGuide);

        Integer id = pcloudGuide.getId();
        List<PcloudGuideMessage> list = new ArrayList<>();
        messageVOList.forEach(item -> {
            PcloudGuideMessage pcloudGuideMessage = new PcloudGuideMessage();
            BeanUtils.copyProperties(item, pcloudGuideMessage);
            pcloudGuideMessage.setPcloudGuideId(id);
            list.add(pcloudGuideMessage);
        });
        pcloudGuideMessageMapper.deleteByGuideId(id);
        pcloudGuideMessageMapper.batchInsert(list);
    }

    @Override
    public PcloudGuideDTO getPcloudGuide(Integer pcloudGuideId) {
        PcloudGuideDTO pcloudGuideVO = new PcloudGuideDTO();
        PcloudGuide pcloudGuide = pcloudGuideMapper.selectByPrimaryKey(pcloudGuideId);
        if (null != pcloudGuide) {
            pcloudGuideVO.setPcloudGuideId(pcloudGuideId);
            pcloudGuideVO.setSeqNum(pcloudGuide.getSeqNum());
            pcloudGuideVO.setTimeSpan(pcloudGuide.getTimeSpan());
            List<PcloudGuideMessageVO> list = pcloudGuideMessageMapper.listByGuideId(pcloudGuideId);
            List<PcloudGuideMessageDTO> messageDTOS = new ArrayList<>();
            if (!ListUtils.isEmpty(list)){
                for (PcloudGuideMessageVO messageVO: list){
                    PcloudGuideMessageDTO messageDTO = new PcloudGuideMessageDTO();
                    BeanUtils.copyProperties(messageVO, messageDTO);
                    messageDTOS.add(messageDTO);
                }
            }
            fillFile(messageDTOS);
            pcloudGuideVO.setMessageDTOS(messageDTOS);
        }
        return pcloudGuideVO;
    }

    private void fillFile(List<PcloudGuideMessageDTO> list){
        if (ListUtils.isEmpty(list)){
            return;
        }
        List<Long> resourceIds = list.stream().filter(s->s.getReplyType().equals(ReplyTypeEnum.RESOURCE.value)).map(PcloudGuideMessageDTO::getResourceId).distinct().collect(Collectors.toList());
        Map<Long, ResourceDTO> resourceDTOMap=new HashMap<>();
        if (!ListUtils.isEmpty(resourceIds)){
            resourceDTOMap = resourceConsr.mapByIds(resourceIds);
        }
        for (PcloudGuideMessageDTO messageDTO:list){
            if (ReplyTypeEnum.RESOURCE.value.equals(messageDTO.getReplyType())){
                ResourceDTO resourceDTO = resourceDTOMap.get(messageDTO.getResourceId());
                if (resourceDTO!=null){
                    messageDTO.setResourceName(resourceDTO.getResourceName());
                    messageDTO.setResourceUrl(resourceDTO.getFileUrl());
                    messageDTO.setResourceTypeCode(resourceDTO.getTypeCode());
                    messageDTO.setResourceTypeName(resourceDTO.getTypeName());
                    messageDTO.setFileType(resourceDTO.getFileType());
                    messageDTO.setResourcePdfItems(resourceDTO.getResourcePdfItems());
                    messageDTO.setResourceOfficeItemDTOs(resourceDTO.getResourceOfficeItemDTOs());
                    messageDTO.setFileSize(resourceDTO.getFileSize());
                }
            }
        }
    }

    @Override
    public PageBeanNew<PcloudGuideDTO> listPcloudGuide(Integer currentPage, Integer numPerPage, String robotWxId, String search, Integer pcloudClassfyId) {
        Integer count = pcloudGuideMapper.getCount(robotWxId, search, pcloudClassfyId);
        List<PcloudGuideDTO> list = new ArrayList<>();
        if (count <= 0) {
            return new PageBeanNew<PcloudGuideDTO>(currentPage, numPerPage, list);
        }
        list = pcloudGuideMapper.listPcloudGuide(currentPage * numPerPage, numPerPage, robotWxId, search, pcloudClassfyId);
        if (!ListUtils.isEmpty(list)){
            List<PcloudGuideMessageDTO> all = new ArrayList<>();
            for (PcloudGuideDTO guideDTO : list){
                List<PcloudGuideMessageDTO> messageDTOS = new ArrayList<>();
                List<PcloudGuideMessageVO> messageList=pcloudGuideMessageMapper.listByGuideId(guideDTO.getPcloudGuideId());
                if (!ListUtils.isEmpty(messageList)){
                    for (PcloudGuideMessageVO messageVO: messageList){
                        PcloudGuideMessageDTO messageDTO = new PcloudGuideMessageDTO();
                        BeanUtils.copyProperties(messageVO, messageDTO);
                        messageDTOS.add(messageDTO);
                    }
                }
                guideDTO.setMessageDTOS(messageDTOS);
                all.addAll(messageDTOS);
            }
            fillFile(all);
        }
        return new PageBeanNew<>(currentPage, numPerPage, count, list);
    }

    @Override
    public void updateSeqNum(UpdateSeqNumVO updateSeqNumVO) {
        pcloudGuideMapper.updateSeqNum(updateSeqNumVO.getPcloudGuideId(), updateSeqNumVO.getSeqNum());
    }

    @Override
    public void create4Robot(Create4RobotVO create4RobotVO) {
        List<Integer> pcloudGuideIds = create4RobotVO.getPcloudGuideIds();
        for (Integer pcloudGuideId : pcloudGuideIds) {
            PcloudGuide pcloudGuide = pcloudGuideMapper.selectByPrimaryKey(pcloudGuideId);
            if (null == pcloudGuide) {
               continue;
            }
            String robotWxId = create4RobotVO.getRobotWxId();
            Integer maxSeqNum = pcloudGuideMapper.getMaxSeqNum(robotWxId, null);
            pcloudGuide.setType(1);
            pcloudGuide.setRobotWxId(robotWxId);
            pcloudGuide.setSeqNum(maxSeqNum +1);
            pcloudGuide.setTimeSpan(pcloudGuide.getTimeSpan());
            pcloudGuideMapper.insert(pcloudGuide);
            List<PcloudGuideMessageVO> messageVOList = pcloudGuideMessageMapper.listByGuideId(pcloudGuideId);
            List<PcloudGuideMessage> list = new ArrayList<>();
            messageVOList.forEach(item -> {
                PcloudGuideMessage pcloudGuideMessage = new PcloudGuideMessage();
                BeanUtils.copyProperties(item, pcloudGuideMessage);
                pcloudGuideMessage.setPcloudGuideId(pcloudGuide.getId());
                list.add(pcloudGuideMessage);
            });
            pcloudGuideMessageMapper.batchInsert(list);
        }
    }

    @Override
    public void setSilenceDuration(RobotSilenceVO robotSilenceVO) {
        if (StringUtil.isEmpty(robotSilenceVO.getRobotWxId()) && null == robotSilenceVO.getPcloudClassifyId()) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数错误！");
        }
        PcloudRobotSilence pcloudRobotSilence = pcloudRobotSilenceMapper.get(robotSilenceVO.getRobotWxId(), robotSilenceVO.getPcloudClassifyId());
        if (null != pcloudRobotSilence) {
            pcloudRobotSilence.setSilenceDuration(robotSilenceVO.getSilenceDuration());
            pcloudRobotSilenceMapper.updateByPrimaryKey(pcloudRobotSilence);
        }else {
            pcloudRobotSilence = new PcloudRobotSilence();
            pcloudRobotSilence.setPcloudClassifyId(robotSilenceVO.getPcloudClassifyId());
            pcloudRobotSilence.setRobotWxId(robotSilenceVO.getRobotWxId());
            pcloudRobotSilence.setSilenceDuration(robotSilenceVO.getSilenceDuration());
            pcloudRobotSilenceMapper.insert(pcloudRobotSilence);
        }
    }

    /**
     * 复制小号的引导语相关设置
     */
    @Override
    public void copyGuideSetting(String fromRobotWxId, String toRobotWxId) {
        List<Integer> pcloudGuideIds = pcloudGuideMapper.listPcloudGuideIds(fromRobotWxId);
        if (!ListUtils.isEmpty(pcloudGuideIds)) {
            Create4RobotVO create4RobotVO = new Create4RobotVO();
            create4RobotVO.setRobotWxId(toRobotWxId);
            create4RobotVO.setPcloudGuideIds(pcloudGuideIds);
            create4Robot(create4RobotVO);
        }
        //设置缄默时长
        Integer silenceDurationByRobotWxId = pcloudRobotSilenceMapper.getSilenceDurationByRobotWxId(fromRobotWxId, null);
        if (null != silenceDurationByRobotWxId) {
            pcloudRobotSilenceMapper.setSilenceDuration(toRobotWxId, silenceDurationByRobotWxId, null);
        }
    }

    @Override
    public void add4Classify(Create4ClassifyVO create4ClassifyVO) {
        List<Integer> pcloudGuideIds = create4ClassifyVO.getPcloudGuideIds();
        for (Integer pcloudGuideId : pcloudGuideIds) {
            PcloudGuide pcloudGuide = pcloudGuideMapper.selectByPrimaryKey(pcloudGuideId);
            if (null == pcloudGuide) {
                continue;
            }
            Integer pcloudClassifyId = create4ClassifyVO.getPcloudClassifyId();
            Integer maxSeqNum = pcloudGuideMapper.getMaxSeqNum(null, pcloudClassifyId);
            pcloudGuide.setType(2);
            pcloudGuide.setRobotWxId(null);
            pcloudGuide.setPcloudClassifyId(pcloudClassifyId);
            pcloudGuide.setSeqNum(maxSeqNum +1);
            pcloudGuide.setTimeSpan(pcloudGuide.getTimeSpan());
            pcloudGuideMapper.insert(pcloudGuide);
            List<PcloudGuideMessageVO> messageVOList = pcloudGuideMessageMapper.listByGuideId(pcloudGuideId);
            List<PcloudGuideMessage> list = new ArrayList<>();
            messageVOList.forEach(item -> {
                PcloudGuideMessage pcloudGuideMessage = new PcloudGuideMessage();
                BeanUtils.copyProperties(item, pcloudGuideMessage);
                pcloudGuideMessage.setPcloudGuideId(pcloudGuide.getId());
                list.add(pcloudGuideMessage);
            });
            pcloudGuideMessageMapper.batchInsert(list);
        }
    }

    @Override
    public void stopPcloudGuidePush(String robotWxId, String userWxId) {
        JedisClusterUtils.hdel(robotWxId + PCLOUD_GUIDE_SUFFIX, userWxId);
    }
}
