package com.pcloud.book.keywords.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.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.group.biz.BookGroupAppBiz;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.enums.AppAndProductTypeEnum;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
import com.pcloud.book.keywords.biz.SelfRobotKeywordBiz;
import com.pcloud.book.keywords.dao.SelfRobotKeywordDao;
import com.pcloud.book.keywords.dto.MaxSeqNAndBGDTO;
import com.pcloud.book.keywords.entity.SelfRobotKeyword;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
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.string.StringUtil;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import com.pcloud.resourcecenter.product.dto.ProductTypeDto;
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.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author ruansiyuan
 * @Date 2019/12/30 11:35
 **/
@Component("selfRobotKeywordBiz")
public class SelfRobotKeywordBizImpl implements SelfRobotKeywordBiz {

    @Autowired
    private SelfRobotKeywordDao selfRobotKeywordDao;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private BookGroupAppBiz bookGroupAppBiz;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("批量新增个人号关键词")
    @Override
    public void batchAddSelfRobotKeyword(Long partyId, List<SelfRobotKeyword> selfRobotKeywords) {
        checkBatchAddSelfRobotKeyword(selfRobotKeywords);
        List<Long> bookGroupIds = selfRobotKeywords.stream().map(SelfRobotKeyword::getBookGroupId).distinct().collect(Collectors.toList());
        List<BookGroupDTO> dtos = bookGroupDao.getDTOByIds(bookGroupIds);
        Map<Long, Long> btcMap = new HashMap<>();
        for (BookGroupDTO bookGroupDTO : dtos) {
            btcMap.put(bookGroupDTO.getId(), bookGroupDTO.getChannelId());
        }
        //获取最大排序值
        List<MaxSeqNAndBGDTO> maxSeqNAndBGDTOS = selfRobotKeywordDao.getMaxSeqNumByBookGroupIds(bookGroupIds);
        Map<Long, Integer> maxSeqMap = new HashMap<>();
        if (!ListUtils.isEmpty(maxSeqNAndBGDTOS)) {
            for (MaxSeqNAndBGDTO maxSeqNAndBGDTO : maxSeqNAndBGDTOS) {
                maxSeqMap.put(maxSeqNAndBGDTO.getBookGroupId(), maxSeqNAndBGDTO.getMaxSeqNum());
            }
        }
        for (SelfRobotKeyword selfRobotKeyword : selfRobotKeywords) {
            selfRobotKeyword.setCreateUser(partyId);
            Long bookGroupId = selfRobotKeyword.getBookGroupId();
            Integer maxSeqNum = maxSeqMap.get(bookGroupId);
            if (maxSeqNum == null) {
                maxSeqNum = 0;
            }
            selfRobotKeyword.setSeqNum(maxSeqNum + 1);
            maxSeqNum = maxSeqNum + 1;
            maxSeqMap.put(bookGroupId, maxSeqNum);
        }
        //新增
        selfRobotKeywordDao.batchInsert(selfRobotKeywords);
        //将作品应用关键词加到社群书应用
        bookGroupAppBiz.addSelfKeywordToBookGroupApp(selfRobotKeywords);
        Map<Long, List<SelfRobotKeyword>> listMap = selfRobotKeywords.stream().filter(s -> AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(s.getServeType())).collect(Collectors.groupingBy(s -> s.getBookGroupId()));
        for (Long bookGroupId : bookGroupIds) {
            List<SelfRobotKeyword> list = listMap.get(bookGroupId);
            if (!ListUtils.isEmpty(list)) {
                List<Long> productIds = list.stream().filter(s -> s.getServeId() != null).map(SelfRobotKeyword::getServeId).collect(Collectors.toList());
                //自动上架
                productConsr.productAutoOnShelves(btcMap.get(bookGroupId), productIds);
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("更新个人号关键词")
    @Override
    public void updateSelfRobotKeyword(Long partyId, SelfRobotKeyword selfRobotKeyword) {
        checkUpdateSelfRobotKeyword(selfRobotKeyword);
        BookGroupDTO dto = bookGroupDao.getDTOById(selfRobotKeyword.getBookGroupId());
        if (dto==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "未找到该社群书！");
        }
        selfRobotKeywordDao.updateSelfRobotKeyword(selfRobotKeyword);
        if (ReplyTypeEnum.APP.value.equals(selfRobotKeyword.getType())
                && AppAndProductTypeEnum.PRODUCT.value.equals(selfRobotKeyword.getServeType())) {
            //上架
            productConsr.productAutoOnShelves(dto.getChannelId(), Arrays.asList(selfRobotKeyword.getServeId()));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("删除个人号关键词")
    @Override
    public void deleteSelfRobotKeyword(Long id) {
        selfRobotKeywordDao.deleteById(id);
    }

    @ParamLog("获取个人号关键词列表")
    @Override
    public PageBeanNew<SelfRobotKeyword> getSelfRobotKeywordList(Long bookGroupId, String keyword, Integer currentPage, Integer numPerPage) {
        if (bookGroupId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "bookGroupId参数为空！");
        }
        if (currentPage == null || numPerPage == null || currentPage < 0 || numPerPage <= 0) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "分页参数错误！");
        }
        PageParam pageParam = new PageParam(currentPage, numPerPage);
        Map<String, Object> map = new HashMap<>();
        map.put("bookGroupId", bookGroupId);
        map.put("keyword", keyword);
        PageBeanNew<SelfRobotKeyword> page = selfRobotKeywordDao.listPageNew(pageParam, map, "getSelfRobotKeywordList");
        fillSelfRobotKeyword(page.getRecordList());
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("删除个人号关键词")
    @Override
    public void updateSelfRobotKeywordSeqNum(SelfRobotKeyword selfRobotKeyword) {
        if (selfRobotKeyword==null||selfRobotKeyword.getId()==null||selfRobotKeyword.getSeqNum()==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        selfRobotKeywordDao.updateSeqNum(selfRobotKeyword.getId(),selfRobotKeyword.getSeqNum());
    }

    @ParamLog("获取应用或作品链接")
    @Override
    public String getAppOrProductServeUrl(Long bookGroupId, Long serveId, String serveType, String serveUrl) {
        if (bookGroupId==null||serveId==null||StringUtil.isEmpty(serveUrl)){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        BookGroupDTO dto = bookGroupDao.getDTOById(bookGroupId);
        if (dto==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数错误！");
        }
        AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(dto.getChannelId());
        if ("APP".equalsIgnoreCase(serveType)) {
            AppDto appDto = appConsr.getBaseById(serveId);
            if (appDto != null) {
                accountSettingDto = qrcodeSceneConsr.getWechatInfo(appDto.getChannelId());
            }
        }
        // 处理链接地址
        String endUrl = serveUrl + "&book_group_id=" + bookGroupId;
        String linkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, endUrl);
        return  linkUrl;
    }

    @Override
    public String getMaxKeyword(Long bookGroupId) {
        List<String> keywords = selfRobotKeywordDao.getKeywords(bookGroupId);
        Integer max = 0;
        for (String keyword : keywords) {
            Integer iKeyword = new Integer(keyword);
            if (iKeyword > max) {
                max = iKeyword;
            }
        }
        return max.toString();
    }

    @ParamLog("填充列表")
    private void fillSelfRobotKeyword(List<SelfRobotKeyword> selfRobotKeywords) {
        if (ListUtils.isEmpty(selfRobotKeywords)){
            return;
        }
        List<Long> appIds=new ArrayList<>();
        List<Long> productIds=new ArrayList<>();
        List<Long> resourceIds=new ArrayList<>();
        for (SelfRobotKeyword selfRobotKeyword:selfRobotKeywords){
            Integer type=selfRobotKeyword.getType();
            if (ReplyTypeEnum.APP.value.equals(type)){
                if (AppAndProductTypeEnum.APP.value.equals(selfRobotKeyword.getServeType())){
                    appIds.add(selfRobotKeyword.getServeId());
                }
                if (AppAndProductTypeEnum.PRODUCT.value.equals(selfRobotKeyword.getServeType())){
                    productIds.add(selfRobotKeyword.getServeId());
                }
            }
            if (ReplyTypeEnum.RESOURCE.value.equals(type)){
                resourceIds.add(selfRobotKeyword.getResourceId());
            }
        }
        Map<Long, AppDto> appDtoMap=new HashMap<>();
        Map<Long, ProductDto> productDtoMap=new HashMap<>();
        Map<Long, ResourceDTO> resourceDTOMap=new HashMap<>();
        if (!ListUtils.isEmpty(appIds)){
            appDtoMap = appConsr.getBaseByIds(appIds);
        }
        if (!ListUtils.isEmpty(productIds)){
            productDtoMap = productConsr.getProBasesByIds(productIds);
        }
        if (!ListUtils.isEmpty(resourceIds)){
            resourceDTOMap = resourceConsr.mapByIds(resourceIds);
        }
        for (SelfRobotKeyword selfRobotKeyword:selfRobotKeywords){
            Integer type=selfRobotKeyword.getType();
            if (ReplyTypeEnum.APP.value.equals(type)){
                Long serveId=selfRobotKeyword.getServeId();
                if (AppAndProductTypeEnum.APP.value.equals(selfRobotKeyword.getServeType())){
                    AppDto appDto=appDtoMap.get(serveId);
                    if (appDto!=null){
                        selfRobotKeyword.setServePic(appDto.getSquareImg());
                        selfRobotKeyword.setServeName(appDto.getTitle());
                        selfRobotKeyword.setServeTypeCode(appDto.getTypeCode());
                        selfRobotKeyword.setServeTypeName(appDto.getTypeName());
                    }
                }
                if (AppAndProductTypeEnum.PRODUCT.value.equals(selfRobotKeyword.getServeType())){
                    ProductDto productDto=productDtoMap.get(serveId);
                    if (productDto!=null){
                        selfRobotKeyword.setServePic(productDto.getCoverImg());
                        selfRobotKeyword.setServeName(productDto.getProductName());
                        ProductTypeDto productTypeDto = productDto.getProductTypeDto();
                        if (productTypeDto!=null){
                            selfRobotKeyword.setServeTypeCode(productTypeDto.getTypeCode());
                            selfRobotKeyword.setServeTypeName(productTypeDto.getTypeName());
                        }
                    }
                }
            }
            if (ReplyTypeEnum.RESOURCE.value.equals(type)){
                ResourceDTO resourceDTO = resourceDTOMap.get(selfRobotKeyword.getResourceId());
                if (resourceDTO!=null){
                    selfRobotKeyword.setResourceName(resourceDTO.getResourceName());
                    selfRobotKeyword.setResourceUrl(resourceDTO.getFileUrl());
                    selfRobotKeyword.setResourceTypeCode(resourceDTO.getTypeCode());
                    selfRobotKeyword.setResourceTypeName(resourceDTO.getTypeName());
                    selfRobotKeyword.setFileType(resourceDTO.getFileType());
                    selfRobotKeyword.setResourcePdfItems(resourceDTO.getResourcePdfItems());
                    selfRobotKeyword.setResourceOfficeItemDTOs(resourceDTO.getResourceOfficeItemDTOs());
                }
            }
        }
    }


    @ParamLog("批量新增个人号关键词参数校验")
    private void checkBatchAddSelfRobotKeyword(List<SelfRobotKeyword> selfRobotKeywords) {
        if (ListUtils.isEmpty(selfRobotKeywords)) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数为空！");
        }
        for (SelfRobotKeyword selfRobotKeyword : selfRobotKeywords) {
            checkAddSelfRobotKeyword(selfRobotKeyword);
        }
    }

    @ParamLog("更新个人号关键词校验")
    private void checkUpdateSelfRobotKeyword(SelfRobotKeyword selfRobotKeyword){
        if (selfRobotKeyword==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数为空！");
        }
        if (selfRobotKeyword.getId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "id不能为空！");
        }
        checkAddSelfRobotKeyword(selfRobotKeyword);
    }

    @ParamLog("校验新增个人号关键词")
    private void checkAddSelfRobotKeyword(SelfRobotKeyword selfRobotKeyword){
        if (selfRobotKeyword==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数为空！");
        }
        if (selfRobotKeyword.getBookGroupId() == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "社群码id不能为空！");
        }
        if (selfRobotKeyword.getType() == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "类型不能为空！");
        }
        if (StringUtil.isEmpty(selfRobotKeyword.getGuide())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "引导语不能为空！");
        }
        if (StringUtil.isEmpty(selfRobotKeyword.getKeyword())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "关键词不能为空！");
        }
        Integer type = selfRobotKeyword.getType();
        if (ReplyTypeEnum.TEXT.value.equals(type) && StringUtil.isEmpty(selfRobotKeyword.getContent())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "内容不能为空！");
        }
        if (ReplyTypeEnum.IMAGE.value.equals(type) && StringUtil.isEmpty(selfRobotKeyword.getPicUrl())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "图片地址不能为空！");
        }
        if (ReplyTypeEnum.LINK.value.equals(type) && StringUtil.isEmpty(selfRobotKeyword.getLinkUrl())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "链接地址不能为空！");
        }
        if (ReplyTypeEnum.APP.value.equals(type) && (StringUtil.isEmpty(selfRobotKeyword.getServeType()) || selfRobotKeyword.getServeId() == null)) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "应用或作品id和类型不能为空！");
        }
        if (ReplyTypeEnum.RESOURCE.value.equals(type) && selfRobotKeyword.getResourceId() == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "资源id和连接不能为空！");
        }
    }
}
