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

import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.group.enums.AppAndProductTypeEnum;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.pcloudkeyword.biz.PcloudKeywordBiz;
import com.pcloud.book.pcloudkeyword.check.PcloudKeywordCheck;
import com.pcloud.book.pcloudkeyword.dao.PcloudKeywordDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudKeywordNameDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudKeywordReplyDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudNotKeywordDao;
import com.pcloud.book.pcloudkeyword.entity.PcloudKeyword;
import com.pcloud.book.pcloudkeyword.entity.PcloudKeywordName;
import com.pcloud.book.pcloudkeyword.entity.PcloudKeywordReply;
import com.pcloud.book.pcloudkeyword.entity.PcloudNotKeyword;
import com.pcloud.book.pcloudkeyword.enums.RelevanceTypeEnum;
import com.pcloud.book.skill.biz.PcloudSkillBiz;
import com.pcloud.book.skill.entity.PcloudSkill;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.BeanUtils;
import com.pcloud.common.utils.ListUtils;
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;


@Component("pcloudKeywordBiz")
public class PcloudKeywordBizImpl implements PcloudKeywordBiz {

    @Autowired
    private PcloudKeywordCheck pcloudKeywordCheck;
    @Autowired
    private PcloudKeywordDao pcloudKeywordDao;
    @Autowired
    private PcloudKeywordNameDao pcloudKeywordNameDao;
    @Autowired
    private PcloudKeywordReplyDao pcloudKeywordReplyDao;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private PcloudNotKeywordDao pcloudNotKeywordDao;
    @Autowired
    private PcloudSkillBiz pcloudSkillBiz;

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("新增平台端关键词")
    @Override
    public void createPcloudKeyword(PcloudKeyword pcloudKeyword) {
        pcloudKeywordCheck.createPcloudKeywordCheck(pcloudKeyword);
        //新增
        String skills = pcloudKeyword.getSkills(pcloudKeyword.getSkillIdList());
        pcloudKeyword.setSkillIds(skills);
        pcloudKeywordDao.insert(pcloudKeyword);
        //新增名称和回复
        createNameAndReply(pcloudKeyword);
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("修改平台端关键词")
    @Override
    public void updatePcloudKeyword(PcloudKeyword pcloudKeyword) {
        pcloudKeywordCheck.updatePcloudKeywordCheck(pcloudKeyword);
        String skills = pcloudKeyword.getSkills(pcloudKeyword.getSkillIdList());
        pcloudKeyword.setSkillIds(skills);
        pcloudKeywordDao.update(pcloudKeyword);
        //删除名称
        pcloudKeywordNameDao.deleteByPcloudKeywordId(pcloudKeyword.getId());
        //删除回复
        pcloudKeywordReplyDao.deleteByRelevance(RelevanceTypeEnum.KEYWORD.value,pcloudKeyword.getId());
        //新增名称和回复
        createNameAndReply(pcloudKeyword);
    }

    @ParamLog("获取平台端关键词")
    @Override
    public PcloudKeyword getPcloudKeyword(Long id) {
        if (id==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"id为空！");
        }
        PcloudKeyword pcloudKeyword = pcloudKeywordDao.getById(id);
        if (pcloudKeyword==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"未找到！");
        }
        List<PcloudKeywordName> names = pcloudKeywordNameDao.getByPcloudKeywordId(id);
        pcloudKeyword.setPcloudKeywordNames(names);
        List<PcloudKeywordReply> replies = pcloudKeywordReplyDao.getByRelevance(RelevanceTypeEnum.KEYWORD.value,id);
        if (!ListUtils.isEmpty(replies)){
            fillReply(replies);
        }
        pcloudKeyword.setPcloudKeywordReplies(replies);
        //技能配置
        List<Long> skills = pcloudKeyword.getSkillList(pcloudKeyword.getSkillIds());
        pcloudKeyword.setSkillIdList(skills);
        if (!ListUtils.isEmpty(skills)){
            List<PcloudSkill> pcloudSkillList =new ArrayList<>();
            for (Long skillId :  skills){
                PcloudSkill pcloudSkill = pcloudSkillBiz.getPcloudSkill(skillId);
                pcloudSkillList.add(pcloudSkill);
            }
            pcloudKeyword.setPcloudSkillList(pcloudSkillList);
        }
        return pcloudKeyword;
    }

    @ParamLog("获取全平台关键词列表")
    @Override
    public PageBeanNew<PcloudKeyword> getPcloudKeywordList(Long keywordClassifyId, String name, Integer currentPage, Integer numPerPage) {
        if (keywordClassifyId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "keywordClassifyId参数为空！");
        }
        if (currentPage == null || numPerPage == null || currentPage < 0 || numPerPage <= 0) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "分页参数错误！");
        }
        Map<String,Object> map=new HashMap<>();
        map.put("keywordClassifyId",keywordClassifyId);
        map.put("name",name);
        PageBeanNew<PcloudKeyword> page = pcloudKeywordDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getPcloudKeywordList");
        if (ListUtils.isEmpty(page.getRecordList())){
            return page;
        }
        List<Long> keywordIds=page.getRecordList().stream().map(PcloudKeyword::getId).collect(Collectors.toList());
        Map<Long,  List<PcloudKeywordName>> nameMap=new HashMap<>();
        Map<Long,  List<PcloudKeywordReply>> replyMap=new HashMap<>();
        List<PcloudKeywordName> names = pcloudKeywordNameDao.getByPcloudKeywordIds(keywordIds);
        List<PcloudKeywordReply> replies=pcloudKeywordReplyDao.getByRelevances(RelevanceTypeEnum.KEYWORD.value,keywordIds);
        if (!ListUtils.isEmpty(names)){
            nameMap=names.stream().collect(Collectors.groupingBy(PcloudKeywordName::getPcloudKeywordId));
        }
        if (!ListUtils.isEmpty(replies)){
            fillReply(replies);
            replyMap=replies.stream().collect(Collectors.groupingBy(PcloudKeywordReply::getRelevanceId));
        }
        for (PcloudKeyword pcloudKeyword:page.getRecordList()){
            pcloudKeyword.setPcloudKeywordNames(nameMap.get(pcloudKeyword.getId()));
            pcloudKeyword.setPcloudKeywordReplies(replyMap.get(pcloudKeyword.getId()));
        }
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("删除全平台关键词列表")
    @Override
    public void deletePcloudKeyword(Long id) {
        if (id==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"id为空！");
        }
        pcloudKeywordDao.deleteById(id);
        pcloudKeywordNameDao.deleteByPcloudKeywordId(id);
        pcloudKeywordReplyDao.deleteByRelevance(RelevanceTypeEnum.KEYWORD.value,id);
    }

    @ParamLog("填充回复")
    private void fillReply(List<PcloudKeywordReply> replies) {
        if(ListUtils.isEmpty(replies)){
            return;
        }
        List<Long> appIds=new ArrayList<>();
        List<Long> resourceIds=new ArrayList<>();
        for (PcloudKeywordReply reply : replies){
            Integer type=reply.getType();
            if (ReplyTypeEnum.APP.value.equals(type)){
                if (AppAndProductTypeEnum.APP.value.equals(reply.getServeType())){
                    appIds.add(reply.getServeId());
                }
            }
            if (ReplyTypeEnum.RESOURCE.value.equals(type)){
                resourceIds.add(reply.getResourceId());
            }
        }
        Map<Long, AppDto> appDtoMap=new HashMap<>();
        Map<Long, ResourceDTO> resourceDTOMap=new HashMap<>();
        if (!ListUtils.isEmpty(appIds)){
            appDtoMap = appConsr.getBaseByIds(appIds);
        }
        if (!ListUtils.isEmpty(resourceIds)){
            resourceDTOMap = resourceConsr.mapByIds(resourceIds);
        }
        for (PcloudKeywordReply reply:replies){
            Integer type=reply.getType();
            if (ReplyTypeEnum.APP.value.equals(type)){
                Long serveId=reply.getServeId();
                if (AppAndProductTypeEnum.APP.value.equals(reply.getServeType())){
                    AppDto appDto=appDtoMap.get(serveId);
                    if (appDto!=null){
                        reply.setServePic(appDto.getSquareImg());
                        reply.setServeName(appDto.getTitle());
                        reply.setServeTypeCode(appDto.getTypeCode());
                        reply.setServeTypeName(appDto.getTypeName());
                    }
                }
            }
            if (ReplyTypeEnum.RESOURCE.value.equals(type)){
                ResourceDTO resourceDTO = resourceDTOMap.get(reply.getResourceId());
                if (resourceDTO!=null){
                    reply.setResourceName(resourceDTO.getResourceName());
                    reply.setResourceUrl(resourceDTO.getFileUrl());
                    reply.setResourceTypeCode(resourceDTO.getTypeCode());
                    reply.setResourceTypeName(resourceDTO.getTypeName());
                    reply.setFileType(resourceDTO.getFileType());
                    reply.setResourcePdfItems(resourceDTO.getResourcePdfItems());
                    reply.setResourceOfficeItemDTOs(resourceDTO.getResourceOfficeItemDTOs());
                    reply.setFileSize(resourceDTO.getFileSize());
                }
            }
        }
    }

    @ParamLog("新增名称和回复")
    private void createNameAndReply(PcloudKeyword pcloudKeyword){
        for (PcloudKeywordName name:pcloudKeyword.getPcloudKeywordNames()){
            name.setPcloudKeywordId(pcloudKeyword.getId());
        }
        pcloudKeywordNameDao.batchInsert(pcloudKeyword.getPcloudKeywordNames());
        for (PcloudKeywordReply reply:pcloudKeyword.getPcloudKeywordReplies()){
            reply.setRelevanceType(RelevanceTypeEnum.KEYWORD.value);
            reply.setRelevanceId(pcloudKeyword.getId());
        }
        pcloudKeywordReplyDao.batchInsert(pcloudKeyword.getPcloudKeywordReplies());
    }

    @Override
    @ParamLog("新增非关键词")
    public Long insertNotKeyword(PcloudNotKeyword pcloudNotKeyword) {
        pcloudKeywordCheck.createPcloudNotKeywordCheck(pcloudNotKeyword);
        //新增
        pcloudNotKeywordDao.insert(pcloudNotKeyword);
        //新增回复
        for (PcloudKeywordReply reply:pcloudNotKeyword.getPcloudKeywordReplies()){
            reply.setRelevanceType(RelevanceTypeEnum.NOT_KEYWORD.value);
            reply.setRelevanceId(pcloudNotKeyword.getId());
        }
        pcloudKeywordReplyDao.batchInsert(pcloudNotKeyword.getPcloudKeywordReplies());
        return pcloudNotKeyword.getId();
    }

    @Override
    @ParamLog("修改非关键词")
    public void updateNotKeyword(PcloudNotKeyword pcloudNotKeyword) {
        pcloudKeywordCheck.updateNotPcloudKeywordCheck(pcloudNotKeyword);
        pcloudNotKeywordDao.update(pcloudNotKeyword);
        //删除回复
        pcloudKeywordReplyDao.deleteByRelevance(RelevanceTypeEnum.NOT_KEYWORD.value,pcloudNotKeyword.getId());
        //新增回复
        for (PcloudKeywordReply reply:pcloudNotKeyword.getPcloudKeywordReplies()){
            reply.setRelevanceType(RelevanceTypeEnum.NOT_KEYWORD.value);
            reply.setRelevanceId(pcloudNotKeyword.getId());
        }
        pcloudKeywordReplyDao.batchInsert(pcloudNotKeyword.getPcloudKeywordReplies());
    }

    @Override
    public void deletePcloudNotKeyword(Long id) {
        if (id==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"id为空！");
        }
        pcloudNotKeywordDao.deleteById(id);
        pcloudKeywordReplyDao.deleteByRelevance(RelevanceTypeEnum.NOT_KEYWORD.value, id);
    }

    @Override
    public PcloudNotKeyword getNotKeywordById(Long id) {
        if (id==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"id为空！");
        }
        PcloudNotKeyword pcloudNotKeyword = pcloudNotKeywordDao.getById(id);
        if (pcloudNotKeyword==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"未找到！");
        }
        List<PcloudKeywordReply> replies = pcloudKeywordReplyDao.getByRelevance(RelevanceTypeEnum.NOT_KEYWORD.value,id);
        if (!ListUtils.isEmpty(replies)){
            fillReply(replies);
        }
        pcloudNotKeyword.setPcloudKeywordReplies(replies);
        return pcloudNotKeyword;
    }

    @Override
    public PageBeanNew<PcloudNotKeyword> getPcloudNotKeywordList(Long keywordClassifyId, Integer currentPage, Integer numPerPage) {
        if (keywordClassifyId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "keywordClassifyId参数为空！");
        }
        if (currentPage == null || numPerPage == null || currentPage < 0 || numPerPage <= 0) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "分页参数错误！");
        }
        Map<String,Object> map=new HashMap<>();
        map.put("keywordClassifyId",keywordClassifyId);
        PageBeanNew<PcloudNotKeyword> page = pcloudNotKeywordDao.listPageNew(new PageParam(currentPage,numPerPage),map,"getPcloudNotKeywordList");
        if (ListUtils.isEmpty(page.getRecordList())){
            return page;
        }
        List<Long> keywordIds=page.getRecordList().stream().map(PcloudNotKeyword::getId).collect(Collectors.toList());
        Map<Long,  List<PcloudKeywordReply>> replyMap=new HashMap<>();
        List<PcloudKeywordReply> replies = pcloudKeywordReplyDao.getByRelevances(RelevanceTypeEnum.NOT_KEYWORD.value, keywordIds);
        if (!ListUtils.isEmpty(replies)){
            fillReply(replies);
            replyMap=replies.stream().collect(Collectors.groupingBy(PcloudKeywordReply::getRelevanceId));
        }
        for (PcloudNotKeyword pcloudNotKeyword:page.getRecordList()){
            pcloudNotKeyword.setPcloudKeywordReplies(replyMap.get(pcloudNotKeyword.getId()));
        }
        return page;
    }

    @Override
    public void deleteByKeywordClassifyId(Long id) {
        //关键词
        List<Long> keywordIds = pcloudKeywordDao.getIdsByClassifyId(id);
        if (!ListUtils.isEmpty(keywordIds)){
            pcloudKeywordReplyDao.deleteByRelevanceIds(RelevanceTypeEnum.KEYWORD.value, keywordIds);
            pcloudKeywordNameDao.deleteByKeywordIds(keywordIds);
        }
        pcloudKeywordDao.deleteByClassifyId(id);
        //非关键词
        List<Long> notKeywordIds = pcloudNotKeywordDao.getIdsByClassifyId(id);
        if (!ListUtils.isEmpty(notKeywordIds)){
            pcloudKeywordReplyDao.deleteByRelevanceIds(RelevanceTypeEnum.NOT_KEYWORD.value, notKeywordIds);
        }
        pcloudNotKeywordDao.deleteByClassifyId(id);
    }

    @Override
    public Boolean skillExist(Long skillId) {
        Boolean exist = pcloudKeywordDao.skillExist(skillId);
        return exist;
    }
}
