/**
 *
 */
package com.pcloud.book.book.set;

import com.google.common.collect.Lists;

import com.alibaba.fastjson.JSONObject;
import com.pcloud.analysisengine.browse.dto.BrowseCacheRecordDto;
import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.appeal.dto.AppealAdviserDto;
import com.pcloud.book.appeal.dto.BookAppealDto;
import com.pcloud.book.appeal.tool.BookAppealTools;
import com.pcloud.book.base.enums.BookFreezeEnum;
import com.pcloud.book.base.enums.BookTypeEnum;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookFundBiz;
import com.pcloud.book.book.dao.BookAdviserDao;
import com.pcloud.book.book.dao.BookFreezeDao;
import com.pcloud.book.book.dao.BookTypeDao;
import com.pcloud.book.book.dto.AdviserManageDto;
import com.pcloud.book.book.dto.BookAdviserDto;
import com.pcloud.book.book.dto.BookAppDto;
import com.pcloud.book.book.dto.BookDeleteDto;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.book.dto.BookFreezeDto;
import com.pcloud.book.book.dto.BookProductDto;
import com.pcloud.book.book.dto.BookResourceDto;
import com.pcloud.book.book.dto.BookTypeDto;
import com.pcloud.book.book.entity.BookDefendant;
import com.pcloud.book.book.tools.BookTools;
import com.pcloud.book.book.vo.NoAuthBookVO;
import com.pcloud.book.consumer.analysisengine.BookScanCountConsr;
import com.pcloud.book.consumer.analysisengine.BrowseRecordConsr;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.common.ExportConsr;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.consumer.message.MessageConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.consumer.settlement.BookConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.book.consumer.user.AgentConsr;
import com.pcloud.book.consumer.user.BookcaseConsr;
import com.pcloud.book.consumer.user.ChannelConsr;
import com.pcloud.book.consumer.user.PartyConsr;
import com.pcloud.book.consumer.voicemessage.MerchantVideoConsr;
import com.pcloud.book.group.biz.BookGroupClassifyBiz;
import com.pcloud.book.group.dao.BookGroupClassifyDao;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.BookGroupStatisticDTO;
import com.pcloud.channelcenter.base.constants.MessageFromTypeEnum;
import com.pcloud.channelcenter.qrcode.dto.QrcodeLocationDto;
import com.pcloud.channelcenter.qrcode.vo.BookAssocLastQrAskVO;
import com.pcloud.channelcenter.qrcode.vo.BookAssocLastQrVO;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.channelcenter.wechat.service.AccountSettingService;
import com.pcloud.comment.base.enums.SysCodeEnum;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.MQTopicProducer;
import com.pcloud.common.core.constant.SystemCode;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.BookUtils;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.common.utils.number.AmountUtil;
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 com.pcloud.resourcecenter.product.dto.SpecificationDto;
import com.pcloud.settlementcenter.record.dto.BookIncomeDto;
import com.pcloud.usercenter.common.dto.BookCaseParamDto;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;
import com.pcloud.usercenter.party.adviser.entity.Adviser;
import com.pcloud.usercenter.party.agent.entity.Agent;
import com.pcloud.voicemessage.party.merchant.entity.MerchantVideo;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
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.stream.Collectors;

/**
 * @描述：图书信息填充
 * @作者：songx
 * @创建时间：2016年12月30日,下午7:40:43 @版本：1.0
 */
@Component("bookSet")
public class BookSet {

    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BookSet.class);

    @Autowired
    private ChannelConsr channelConsr;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private BookcaseConsr bookcaseConsr;
    @Autowired
    private BookScanCountConsr bookScanCountConsr;
    @Autowired
    private MerchantVideoConsr merchantVideoConsr;
    @Autowired
    private PartyConsr partyConsr;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private BookConsr bookConsr;
    @Autowired
    private BookAdviserDao bookAdviserDao;
    @Autowired
    private BookTypeDao bookTypeDao;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private BrowseRecordConsr browseRecordConsr;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private BookFundBiz bookFundBiz;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private MessageConsr messageConsr;
    @Autowired
    private BookFreezeDao bookFreezeDao;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private AgentConsr agentConsr;
    @Autowired
    private AccountSettingService accountSettingService;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private BookGroupClassifyBiz bookGroupClassifyBiz;
    @Autowired
    private BookGroupClassifyDao bookGroupClassifyDao;

    /**
     * 检验书号是否合法，包括ISSN,ISBN,CSSN
     * @param typeCode 类型，图书或者期刊
     * @param isbn
     */
    public void checkISBNEx(String typeCode, String isbn) {
        // 判断书籍ISBN码是否符合规范
        if (BookTypeEnum.BOOK.value.equals(typeCode) && !BookUtils.checkISBN(isbn)) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "ISBN码格式不符合标准");
        } else if (BookTypeEnum.JOURNAL.value.equals(typeCode)) {
            // 判断CSSN和ISSN编码是否符合规范
            if (isbn.startsWith("CN")) {
                String number = isbn.substring(2, isbn.lastIndexOf("/"));
                if (number.length() != 6 || !NumberUtils.isDigits(number)) {
                    throw new BookBizException(BookBizException.PARAM_IS_ERROR, "CSSN码格式不符合标准");
                }
            } else if (!BookUtils.checkISSN(isbn)) {
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "ISSN码格式不符合标准");
            }
        }
    }

    /**
     * 检验书号是否合法
     * @param typeCode 类型，图书
     * @param isbn
     */
    public void checkISBN(String typeCode, String isbn) throws BizException {
        // 判断书籍ISBN码是否符合规范
        if (BookTypeEnum.BOOK.value.equals(typeCode) && !BookUtils.checkISBN(isbn)) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "ISBN码格式不符合标准");
        }
    }

    /**
     * 验证issn，CSSN
     * @param typeCode
     * @param issn
     */
    public void checkISSN(String typeCode, String issn) throws BizException {
        try {
            if (BookTypeEnum.JOURNAL.value.equals(typeCode)) {
                if (issn.toUpperCase().trim().startsWith("CN")) {
                    if (issn.contains("-")) {
                        String startIndex = issn.substring(2, issn.lastIndexOf("-"));
                        String endIndex = issn.substring(issn.lastIndexOf("-") + 1);
                        if (issn.contains("/")) {
                            endIndex = issn.substring(issn.lastIndexOf("-") + 1, issn.lastIndexOf("/"));
                        }
                        if (startIndex.length() != 2 || !NumberUtils.isDigits(startIndex) || endIndex.length() != 4
                                || !NumberUtils.isDigits(endIndex)) {
                            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "CN码格式不符合标准");
                        }
                    } else {
                        String index = issn.substring(2);
                        if (issn.contains("/")) {
                            index = issn.substring(2, issn.lastIndexOf("/"));
                        }
                        if (index.length() != 6 || !NumberUtils.isDigits(index)) {
                            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "CN码格式不符合标准");
                        }
                    }
                } else {
                    if (!BookUtils.checkISSN(issn)) {
                        throw new BookBizException(BookBizException.PARAM_IS_ERROR, "ISSN码格式不符合标准");
                    }

                }
            }
        } catch (Exception e) {
            LOGGER.info("校验CN/ISSN码出现异常：" + e);
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "ISSN号或CN类刊号格式不符合标准");
        }
    }

    /**
     * 批量填充渠道信息
     */
    public void setChannelInfoList(List<Object> objects) throws BizException {
        // 组装运营标识(去重)
        List<Long> channelIds = BookTools.listChannelIds(objects);
        // 从用户中心批量获取渠道名称
        Map<Long, String> channelNameMap = channelConsr.getNamesByIdList(channelIds);
        if (MapUtils.isEmpty(channelNameMap)) {
            return;
        }
        // 批量填充运营信息
        BookTools.setChannelNames(objects, channelNameMap);
    }

    /**
     * 批量填充渠道公众号信息
     */
    public void setChannelOfficialAccountInfoList(List<Object> objects) throws BizException {
        // 组装运营标识(去重)
        List<Long> channelIds = BookTools.listChannelIds(objects);
        if (ListUtils.isEmpty(channelIds)) {
            return;
        }
        // 从渠道中心批量获取渠道公众号名称
        Map<Long, AccountSettingDto> officialAccountNameMap = ResponseHandleUtil.parseMap(accountSettingService.listWechat(channelIds), Long.class, AccountSettingDto.class);
        if (MapUtils.isEmpty(officialAccountNameMap)) {
            return;
        }
        // 批量填充运营公众号信息
        BookTools.setChannelOfficialAccountsNames(objects, officialAccountNameMap);
    }

    /**
     * 批量填充顾问名称
     */
    public void setAdviserName4BookDto(List<Object> objects) {
        // 组装编辑标识(去重)
        List<Long> adviserIds = BookTools.listAdviserIds(objects);
        // 从用户中心批量获取编辑名称
        Map<Long, String> adviserNameMap = adviserConsr.getNames(adviserIds);
        if (MapUtils.isEmpty(adviserNameMap)) {
            return;
        }
        // 批量填充编辑名称
        BookTools.setAdviserNames(objects, adviserNameMap);
    }

    /**
     * 批量填充出版ID
     */
    public void setAgentId4BookDto(List<Object> objects) {
        for (Object object : objects) {
            BookDto bookDto = (BookDto) object;
            Long adviserId = bookDto.getAdviserId();
            if (null != adviserId) {
                Long agentId = adviserConsr.getAgentIdByAdviser(adviserId);
                bookDto.setAgentId(agentId);
            }
        }
    }

    /**
     * 批量填充出版名称
     */
    public void setAgentName4BookDto(List<Object> objects) {
        // 组装出版标识(去重)
        List<Long> agentIds = BookTools.listAgentIds(objects);
        // 从用户中心批量获取出版名称
        Map<Long, String> agentNameMap = agentConsr.getNames(agentIds);
        if (MapUtils.isEmpty(agentNameMap)) {
            return;
        }
        // 批量填充出版名称
        BookTools.setAgentNames(objects, agentNameMap);
    }


    /**
     * 批量填充顾问名称
     */
    public void setAdviserName(List<Object> objects) {
        // 组装编辑标识(去重)
        List<Long> adviserIds = BookAppealTools.listAdviserIds(objects);
        // 从用户中心批量获取编辑名称
        Map<Long, String> adviserNameMap = adviserConsr.getNames(adviserIds);
        if (MapUtils.isEmpty(adviserNameMap)) {
            return;
        }
        // 批量填充编辑名称
        BookAppealTools.setAdviserNames(objects, adviserNameMap);
    }

    /**
     * 设置申诉方及被诉方基本信息
     * @param bookAppealDto
     */
    public void setAdviserInfo(BookAppealDto bookAppealDto) {
        List<Long> adviserIds = new ArrayList<>();
        List<Long> channelIds = new ArrayList<>();
        Long channelId = bookAppealDto.getChannelId();
        channelIds.add(channelId);
        List<BookDefendant> bookDefendants = new ArrayList<>();
        List<BookAdviserDto> defendantAdvisers = null;
        if (!bookAppealDto.getAppealState().equals(0)) {// 已审核
            bookDefendants = bookAppealDto.getDefendants();
            bookDefendants.stream().forEach(
                    bookDefendant -> {
                        if (!adviserIds.contains(bookDefendant.getAdviserId())) {
                            adviserIds.add(bookDefendant.getAdviserId());
                        }
                        if (!channelIds.contains(bookDefendant.getChannelId())) {
                            channelIds.add(bookDefendant.getChannelId());
                        }
                    }
            );
        } else {// 未审核状态
            // 获取被诉方信息(即与该书关联的所有编辑)
            defendantAdvisers = bookAdviserDao.getAdvisers(bookAppealDto.getBookId());
            defendantAdvisers.stream().forEach(
                    adviser -> {
                        if (!adviserIds.contains(adviser.getAdviserId())) {
                            adviserIds.add(adviser.getAdviserId());
                        }
                        if (!channelIds.contains(adviser.getChannelId())) {
                            channelIds.add(adviser.getChannelId());
                        }
                        if (!channelId.equals(adviser.getChannelId())) {
                            bookAppealDto.setHaveDiffChannel(true);
                        }
                    }
            );
        }

        // 加上申诉方
        if (!adviserIds.contains(bookAppealDto.getDeclarant())) {
            adviserIds.add(bookAppealDto.getDeclarant());
        }

        // 获取基本信息
        Map<Long, AdviserBaseInfoDto> adviserMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(adviserIds);
        Map<Long, String> channelNameMap = channelConsr.getNamesByIdList(channelIds);

        // 设置申诉方所属出版社名称
        if (adviserMap != null && adviserMap.get(bookAppealDto.getDeclarant()) != null) {
            bookAppealDto.setAgentName(adviserMap.get(bookAppealDto.getDeclarant()).getAgentName());
            bookAppealDto.setDeclarantName(adviserMap.get(bookAppealDto.getDeclarant()).getPartyName());
        }
        if (channelNameMap != null) {
            bookAppealDto.setChannelName(channelNameMap.get(channelId));
        }
        if (!ListUtils.isEmpty(defendantAdvisers)) {// 未审核
            // 设置被诉方基本信息
            for (BookAdviserDto bookAdviserDto : defendantAdvisers) {
                if (adviserMap != null && adviserMap.get(bookAdviserDto.getAdviserId()) != null) {
                    BookDefendant bookDefendant = new BookDefendant();
                    bookDefendant.setAgentName(adviserMap.get(bookAdviserDto.getAdviserId()).getAgentName());
                    bookDefendant.setAdviserName(adviserMap.get(bookAdviserDto.getAdviserId()).getPartyName());
                    bookDefendant.setPhone(adviserMap.get(bookAdviserDto.getAdviserId()).getPhoneNum());
                    bookDefendant.setCreatedDate(bookAdviserDto.getCreatedDate());
                    bookDefendant.setChannelId(bookAdviserDto.getChannelId());
                    bookDefendant.setAdviserId(bookAdviserDto.getAdviserId());
                    bookDefendant.setBookAppealId(bookAppealDto.getBookAppealId());
                    bookDefendant.setIsMainEditor(bookAdviserDto.getIsMainEditor());
                    bookDefendant.setCoverImg(adviserMap.get(bookAdviserDto.getAdviserId()).getHeadUrl());
                    if (channelNameMap != null) {
                        bookDefendant.setChannelName(channelNameMap.get(bookDefendant.getChannelId()));
                    }
                    bookDefendants.add(bookDefendant);
                }
            }
            bookAppealDto.setDefendants(bookDefendants);
        } else {// 已审核
            for (BookDefendant bookDefendant : bookDefendants) {
                if (adviserMap != null && adviserMap.get(bookDefendant.getAdviserId()) != null) {
                    bookDefendant.setAgentName(adviserMap.get(bookDefendant.getAdviserId()).getAgentName());
                    bookDefendant.setAdviserName(adviserMap.get(bookDefendant.getAdviserId()).getPartyName());
                    bookDefendant.setPhone(adviserMap.get(bookDefendant.getAdviserId()).getPhoneNum());
                    bookDefendant.setCoverImg(adviserMap.get(bookDefendant.getAdviserId()).getHeadUrl());
                    if (channelNameMap != null) {
                        bookDefendant.setChannelName(channelNameMap.get(bookDefendant.getChannelId()));
                    }
                }
            }
        }

    }

    /**
     * 设置书籍是否加入书架
     * @param recordList
     */
    public void setIsHaveAddBookcase(List<Object> recordList, Long wechatUserId) {
        List<BookCaseParamDto> bcpDtoList = new ArrayList<BookCaseParamDto>();
        for (Object book : recordList) {
            BookCaseParamDto bcpDto = new BookCaseParamDto();
            BookDto bookDto = (BookDto) book;
            bcpDto.setBookId(bookDto.getBookId());
            bcpDto.setAdviserId(bookDto.getAdviserId());
            bcpDto.setChannelId(bookDto.getChannelId());
            bcpDto.setWechatUserId(wechatUserId);
            bcpDtoList.add(bcpDto);
        }
        Map<Long, Boolean> resultMap = bookcaseConsr.judgeBookExist(bcpDtoList);
        if (resultMap != null) {
            for (Object book : recordList) {
                BookDto bookDto = (BookDto) book;
                if (resultMap.containsKey(bookDto.getBookId())) {
                    bookDto.setIsSelect(resultMap.get(bookDto.getBookId()));
                }
            }
        }
    }

    /**
     * 发送书籍删除topic
     * @param bookId 书籍标识
     */
    public void sendBookDeleteTopic(Long bookId) {
        LOGGER.info("【书籍基础】发送书籍删除topic,<START>bookId:{}", bookId);
        BookDeleteDto bookDeleteDto = new BookDeleteDto();
        List<Long> bookIds = new ArrayList<>();
        bookIds.add(bookId);
        bookDeleteDto.setBookIds(bookIds);
        try {
            amqpTemplate.convertAndSend(MQTopicProducer.EXCHAGE, MQTopicProducer.BOOK_DELETE, bookDeleteDto);
        } catch (Exception e) {
            LOGGER.error("【书籍基础】发送书籍删除topic,<ERROR>", e);
        }
    }

    /**
     * 批量删除书籍topic
     * @param bookIds
     */
    public void sendBooksDeleteTopic(List<Long> bookIds) {
        LOGGER.info("【书籍基础】发送批量删除书籍topic,<START>bookIds:{}", bookIds);
        BookDeleteDto bookDeleteDto = new BookDeleteDto();
        bookDeleteDto.setBookIds(bookIds);
        try {
            amqpTemplate.convertAndSend(MQTopicProducer.EXCHAGE, MQTopicProducer.BOOK_DELETE, bookDeleteDto);
        } catch (Exception e) {
            LOGGER.error("【书籍基础】发送批量删除书籍topic,<ERROR>", e);
        }
    }

    /**
     * 设置被诉方
     * @param adviserBooks
     * @param bookAppealId
     */
    public List<BookDefendant> setDefendant(List<BookAdviserDto> adviserBooks, Long bookAppealId) {
        List<BookDefendant> bookDefendants = new ArrayList<>();
        if (!ListUtils.isEmpty(adviserBooks)) {
            for (BookAdviserDto bookAdviserDto : adviserBooks) {
                BookDefendant bookDefendant = new BookDefendant();
                bookDefendant.setCreatedDate(bookAdviserDto.getCreatedDate());
                bookDefendant.setAdviserId(bookAdviserDto.getAdviserId());
                bookDefendant.setChannelId(bookAdviserDto.getChannelId());
                bookDefendant.setBookAppealId(bookAppealId);
                bookDefendant.setIsMainEditor(bookAdviserDto.getIsMainEditor());
                bookDefendants.add(bookDefendant);
            }
        }
        return bookDefendants;
    }

    /**
     * 设置申诉和被诉编辑信息
     * @param appealAdviserList
     * @param bookAppealDto     申诉方
     * @param defendantAdvisers 被诉方
     */
    public void setAppealAdviserList(List<AppealAdviserDto> appealAdviserList, BookAppealDto bookAppealDto,
            List<BookAdviserDto> defendantAdvisers) {
        if (bookAppealDto == null) {
            return;
        }
        List<Long> adviserIds = new ArrayList<>();
        List<Long> channelIds = new ArrayList<>();
        Long bookId = bookAppealDto.getBookId();
        Long channelId = bookAppealDto.getChannelId();
        Long adviserId = bookAppealDto.getDeclarant();
        adviserIds.add(adviserId);
        channelIds.add(channelId);
        // 申诉人信息
        AppealAdviserDto adviserDto = new AppealAdviserDto();
        adviserDto.setBookId(bookId);
        adviserDto.setChannelId(channelId);
        adviserDto.setAdviserId(adviserId);
        appealAdviserList.add(adviserDto);
        // 被申诉人信息
        for (BookAdviserDto bookAdviserDto : defendantAdvisers) {
            AppealAdviserDto defendantAdviserDto = new AppealAdviserDto();
            defendantAdviserDto.setBookId(bookId);
            defendantAdviserDto.setChannelId(bookAdviserDto.getChannelId());
            defendantAdviserDto.setAdviserId(bookAdviserDto.getAdviserId());
            defendantAdviserDto.setIsMainEditor(bookAdviserDto.getIsMainEditor());
            appealAdviserList.add(defendantAdviserDto);
            adviserIds.add(bookAdviserDto.getAdviserId());
            channelIds.add(bookAdviserDto.getChannelId());
        }
        // 获取编辑名称
        Map<Long, String> adviserNameMap = adviserConsr.getNames(adviserIds);
        //获取运营平台名称
        Map<Long, String> channelNameMap = channelConsr.getNamesByIdList(channelIds);
        if (MapUtils.isEmpty(adviserNameMap)) {
            return;
        }
        for (AppealAdviserDto adviser : appealAdviserList) {
            if (!MapUtils.isEmpty(adviserNameMap)) {
                adviser.setAdviserName(adviserNameMap.get(adviser.getAdviserId()));
            }
            if (!MapUtils.isEmpty(channelNameMap)) {
                adviser.setChannelName(channelNameMap.get(adviser.getChannelId()));
            }
        }
    }

    /**
     * 设置编辑详细信息
     * @param adviserManageDtos
     * @param adviserIds
     * @return: void
     * @author: lihao
     * @date: 2017年7月12日 上午11:52:40
     */
    public void setAdviserDetailInfo(List<AdviserManageDto> adviserManageDtos, List<Long> adviserIds) {
        // 获取编辑名称
        Map<Long, String> adviserNameMap = adviserConsr.getNames(adviserIds);
        List<Long> channelIds = new ArrayList<>();
        for (AdviserManageDto adviserManageDto : adviserManageDtos) {
            channelIds.add(adviserManageDto.getChannelId());
            List<BookAdviserDto> bookAdviserDtos = adviserManageDto.getAdviserList();
            if (null != bookAdviserDtos && bookAdviserDtos.size() != 0) {
                for (BookAdviserDto bookAdviserDto : adviserManageDto.getAdviserList()) {
                    // 设置编辑名称
                    if (bookAdviserDto != null && adviserNameMap.containsKey(bookAdviserDto.getAdviserId())) {
                        bookAdviserDto.setAdviserName(adviserNameMap.get(bookAdviserDto.getAdviserId()));
                    }
                }
            }
        }
        // 获取渠道名称
        Map<Long, String> channelNameMap = channelConsr.getNamesByIdList(channelIds);
        // 渠道IDs获取代理信息
        Map<Long, Agent> agentInfoMap = partyConsr.getAgentByPartyId(channelIds, SysCodeEnum.CHANNEL.value);
        for (AdviserManageDto adviserManageDto : adviserManageDtos) {
            // 设置渠道名称
            if (channelNameMap.containsKey(adviserManageDto.getChannelId())) {
                adviserManageDto.setChannelName(channelNameMap.get(adviserManageDto.getChannelId()));
            }
            // 设置渠道名称
            if (agentInfoMap.containsKey(adviserManageDto.getChannelId())
                    && agentInfoMap.get(adviserManageDto.getChannelId()) != null) {
                adviserManageDto.setAgentName(agentInfoMap.get(adviserManageDto.getChannelId()).getName());
            }
        }
    }

    /**
     * @param bookDto
     * @param mainAdviserId
     * @Description:设置主编辑信息
     * @author: lihao
     * @date: 2017年7月12日 下午6:46:48
     */
    public void setMainEditorInfo(BookDto bookDto, Long mainAdviserId) {
        Adviser adviser = adviserConsr.getById(mainAdviserId);
        if (adviser != null) {
            bookDto.setMainEditorName(adviser.getName());
            bookDto.setMainEditorPic(adviser.getImgUrl());
        }
    }

    /**
     * @param recordList
     * @Description:设置微信端书刊列表详细信息
     * @return: void
     * @author: lihao
     * @date: 2017年7月18日 下午8:07:15
     */
    public void setPageDetailInfo4Wechat(List<Object> recordList, Long adviserId) {
        if (recordList == null || ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> channelIds = new ArrayList<>();
        List<Long> bookIds = new ArrayList<>();
        for (Object obj : recordList) {
            BookDto bookDto = (BookDto) obj;
            if (null != bookDto) {
                channelIds.add(bookDto.getChannelId());
                bookIds.add(bookDto.getBookId());

            }
        }
        // 从用户中心批量获取渠道名称
        Map<Long, String> channelNameMap = channelConsr.getNamesByIdList(channelIds);
        // 从用户中心获取编辑名称
        String adviserName = adviserConsr.getNameById(adviserId);
        // 获取书籍扫描数
        Map<String, Long> bookScanCountMap = bookScanCountConsr.listBookScanCount(bookIds, channelIds, adviserId);
        // 获取书籍二维码数
        Map<String, Long> bookQrCountMap = qrcodeSceneConsr.listBookQrCount(bookIds, channelIds, adviserId);
        // 获取书刊收益和读者数信息
        Map<String, BookIncomeDto> bookIncomeMap = bookConsr.getBookIncomeInfo(bookIds, channelIds, adviserId);
        // 获取基金收益
        Map<Long, BigDecimal> bookFundMoneyMap = bookFundBiz.getBookFundMoney(bookIds);

        for (Object obj : recordList) {
            BookDto bookDto = (BookDto) obj;
            if (null != bookDto) {
                // 设置渠道名称
                if (null != channelNameMap && channelNameMap.containsKey(bookDto.getChannelId())) {
                    bookDto.setChannelName(channelNameMap.get(bookDto.getChannelId()));
                }
                String key = bookDto.getBookId() + "-" + bookDto.getChannelId();
                // 设置书籍扫描数
                if (null != bookScanCountMap && bookScanCountMap.containsKey(key)) {
                    bookDto.setBookScanCount(bookScanCountMap.get(key));
                }
                // 设置书籍二维码数
                if (null != bookQrCountMap && bookQrCountMap.containsKey(key)) {
                    bookDto.setBookQrCount(bookQrCountMap.get(key));
                }
                // 设置书刊收益和读者数信息
                if (null != bookIncomeMap && bookIncomeMap.containsKey(key) && null != bookIncomeMap.get(key)) {
                    bookDto.setReaderCount(bookIncomeMap.get(key).getReadersCount());
                    bookDto.setBookIncome(bookIncomeMap.get(key).getIncome());
                }
                // 设置主编辑名称
                if (bookDto.getIsMainEditor()) {// 是主编辑
                    bookDto.setMainEditorName(adviserName);
                    if (bookFundMoneyMap != null) {
                        bookDto.setFundMoney(bookFundMoneyMap.get(bookDto.getBookId()));
                        if (bookDto.getBookIncome() != null && bookDto.getFundMoney() != null) {
                            bookDto.setBookIncome(bookDto.getBookIncome().subtract(bookDto.getFundMoney()));
                        }
                    }
                } else {// 不是主编辑
                    Long mainAdviserId = bookAdviserDao.getMainAdviserId(bookDto.getBookId(), bookDto.getChannelId());
                    String mainAdviserName = adviserConsr.getNameById(mainAdviserId);
                    bookDto.setMainEditorName(mainAdviserName);
                }
            }
        }
    }

    public void setPageDetailInfo4Platform(List<BookDto> list) {
        List<Long> bookIds = new ArrayList<>();
        for (BookDto bookDto : list) {
            if (bookDto != null) {
                bookIds.add(bookDto.getBookId());
            }
        }
        // 根据bookIds查询书刊编辑关联信息
        Map<Long, BookAdviserDto> bookAdviserMap = bookAdviserDao.getByBookIds(bookIds);
        // 根据bookIds查询书刊基金关联信息
        // Map<Long, BookFundDto> bookFundMap =
        // bookFundDao.getByBookIds(bookIds);
        // 获取图书类型名称
        Map<String, BookTypeDto> typeCodeMap = bookTypeDao.getTypeCodeMap();
        // 设置基金冻结状态
        Map<Long, BookFreezeDto> freezeStatus = bookFreezeDao.getIsFreeze(bookIds);
        for (BookDto bookDto : list) {
            if (bookDto != null) {
                // 设置图书是否存在编辑
                BookAdviserDto bookAdviserDto = bookAdviserMap.get(bookDto.getBookId());
                Boolean isHaveAdviser = bookAdviserDto == null ? false : true;
                if (freezeStatus != null && freezeStatus.get(bookDto.getBookId()) != null) {
                    bookDto.setFreezeStatus(BookFreezeEnum.FREEZE.value);
                }
                bookDto.setIsHaveAdviser(isHaveAdviser);
                // 设置图书类型名称
                if (null != typeCodeMap && typeCodeMap.get(bookDto.getTypeCode()) != null) {
                    String typeName = typeCodeMap.get(bookDto.getTypeCode()).getTypeName();
                    bookDto.setTypeName(typeName);
                }
                // // 设置图书是否有基金支持和是否有基金
                // BookFundDto bookFundDto =
                // bookFundMap.get(bookDto.getBookId());
                // if(bookFundDto == null){
                // bookDto.setIsFundSupport(false);
                // }else{
                // bookDto.setIsFundSupport(true);
                // }
            }
        }

    }

    /**
     * 设置应用基本信息(过滤审核不通过的与过期的应用)
     * @param bookAppDtos
     * @return
     */
    public List<BookAppDto> setPassAppInfo(List<BookAppDto> bookAppDtos) {
        List<BookAppDto> bookAppDtoNew = new ArrayList<>();
        if (ListUtils.isEmpty(bookAppDtos)) {
            return bookAppDtoNew;
        }
        List<Long> appIds = new ArrayList<>();
        for (BookAppDto bookAppDto : bookAppDtos) {
            appIds.add(bookAppDto.getAppId());
        }
        if (ListUtils.isEmpty(appIds)) {
            return bookAppDtoNew;
        }
        Map<Long, AppDto> appDtos = appConsr.listPassById(appIds);
        if (!ListUtils.isEmpty(appIds)) {
            for (BookAppDto bookAppDto : bookAppDtos) {
                AppDto appDto = appDtos.get(bookAppDto.getAppId());
                if (appDto != null) {
                    bookAppDto.setTitle(appDto.getTitle());
                    bookAppDto.setSquareImg(appDto.getSquareImg());
                    bookAppDto.setTransverseImg(appDto.getTransverseImg());
                    bookAppDto.setTypeCode(appDto.getTypeCode());
                    bookAppDto.setTypeName(appDto.getTypeName());
                    bookAppDto.setRemark(appDto.getRemark());
                    bookAppDtoNew.add(bookAppDto);
                }
            }
        }
        return bookAppDtoNew;
    }

    /**
     * 设置录音并转换为map
     * @param bookProductDtos
     * @return
     */
    public Map<Long, BookProductDto> setSoundInfoAndToMap(List<BookProductDto> bookProductDtos) {
        Map<Long, BookProductDto> bookProducts = new HashMap<>();
        List<Long> soundIds = new ArrayList<>();
        if (!ListUtils.isEmpty(bookProductDtos)) {
            for (BookProductDto bookProductDto : bookProductDtos) {
                if (bookProductDto != null && bookProductDto.getSoundId() != null) {
                    soundIds.add(bookProductDto.getSoundId());
                }
            }
            // 调用用户中心查询录音信息
            Map<Long, MerchantVideo> soundInfos = merchantVideoConsr.getVideoById(soundIds);
            for (BookProductDto bookProductDto : bookProductDtos) {
                if (bookProductDto.getSoundId() != null && soundInfos != null) {
                    MerchantVideo merchantVideo = soundInfos.get(bookProductDto.getSoundId());
                    if (merchantVideo != null) {
                        bookProductDto.setSoundType(merchantVideo.getVideoType());
                        bookProductDto.setSoundUrl(merchantVideo.getVideoPath());
                        bookProductDto.setFileSize(merchantVideo.getVideoSize());
                        bookProductDto.setSoundName(merchantVideo.getVideoShortName());
                    }
                }
                bookProducts.put(bookProductDto.getProductId(), bookProductDto);
            }
        }
        return bookProducts;
    }

    /**
     * 设置应用基本信息
     * @param bookAppDtos
     */
    public void setAppInfo(List<BookAppDto> bookAppDtos) {
        if (ListUtils.isEmpty(bookAppDtos)) {
            return;
        }
        List<Long> appIds = new ArrayList<>();
        for (BookAppDto bookAppDto : bookAppDtos) {
            if (bookAppDto.getAppId() != null) {
                appIds.add(bookAppDto.getAppId());
            }
        }
        // 设置应用信息
        Map<Long, AppDto> appDtos = appConsr.mapByIds(appIds);
        for (BookAppDto bookAppDto : bookAppDtos) {
            if (bookAppDto.getAppId() != null) {
                AppDto appDto = appDtos.get(bookAppDto.getAppId());
                if (appDto != null) {
                    bookAppDto.setTitle(appDto.getTitle());
                    bookAppDto.setSquareImg(appDto.getSquareImg());
                    bookAppDto.setTypeName(appDto.getTypeName());
                    bookAppDto.setTypeCode(appDto.getTypeCode());
                    bookAppDto.setOverdue(appDto.getOverdue());
                    bookAppDto.setAppCreatedDate(appDto.getCreatedDate());
                }
            }
        }

    }

    /**
     * 设置是否配置过录音
     * @param bookProductAssoc
     */
    public void setIsHaveSound(List<BookProductDto> bookProductAssoc) {
        if (ListUtils.isEmpty(bookProductAssoc)) {
            return;
        }
        List<Long> productIds = new ArrayList<>();
        for (BookProductDto bookProductDto : bookProductAssoc) {
            if (bookProductDto != null) {
                productIds.add(bookProductDto.getProductId());
            }
        }
        // 获取商品是否包含录音
        Map<Long, MerchantVideo> IsHaveSoundMap = merchantVideoConsr.getVideoByObjectId(productIds,
                MessageFromTypeEnum.PRODUCT.value);
        for (BookProductDto bookProductDto : bookProductAssoc) {
            if (bookProductDto != null) {

                if (IsHaveSoundMap.get(bookProductDto.getProductId()) != null) {
                    MerchantVideo merchantVideo = IsHaveSoundMap.get(bookProductDto.getProductId());
                    if (merchantVideo != null && merchantVideo.getVideoId() != null && merchantVideo.getVideoId() > 0) {
                        bookProductDto.setSoundStatus(true);
                    } else {
                        bookProductDto.setSoundStatus(false);
                    }
                } else {
                    bookProductDto.setSoundStatus(false);
                }
            }
        }
    }

    /**
     * 设置商品基本信息
     * @param bookProductAssoc
     */
    public void setProductInfo(List<BookProductDto> bookProductAssoc, Long channelId) {
        if (ListUtils.isEmpty(bookProductAssoc)) {
            return;
        }
        List<Long> productIds = new ArrayList<>();
        for (BookProductDto bookProductDto : bookProductAssoc) {
            if (bookProductDto != null) {
                productIds.add(bookProductDto.getProductId());
            }
        }
        Map<Long, ProductDto> productMap = productConsr.listProDetail4Wechat(productIds, channelId);
        if (MapUtils.isEmpty(productMap)) {
            return;
        }
        for (BookProductDto bookProductDto : bookProductAssoc) {
            ProductDto productDto = productMap.get(bookProductDto.getProductId());
            if (productDto != null) {
                bookProductDto.setProductName(productDto.getProductName());
                ProductTypeDto productTypeDto = productDto.getProductTypeDto();
                if (productTypeDto != null) {
                    bookProductDto.setProductType(productTypeDto.getTypeCode());
                    bookProductDto.setProductTypeName(productTypeDto.getTypeName());
                }
                List<SpecificationDto> specifications = productDto.getSpecification();
                if (!ListUtils.isEmpty(specifications)) {
                    for (SpecificationDto specificationDto : specifications) {
                        bookProductDto.setPrice(specificationDto.getRetailPrice());
                    }
                }
                bookProductDto.setCoverImg(productDto.getCoverImg());

                bookProductDto.setIsSale(productDto.getIsSale());

                bookProductDto.setMerchantName(productDto.getMerchantName());
            }
        }
    }

    /**
     * 设置资源文件
     * @param bookResources
     */
    public List<Object> listResourceFile(List<BookResourceDto> bookResources) {
        List<Object> resourceFiles = new ArrayList<>();
        List<ResourceDTO> passResource = new ArrayList<>();
        if (!ListUtils.isEmpty(bookResources)) {
            List<Long> resourceIds = new ArrayList<>();
            for (BookResourceDto bookResourceDto : bookResources) {
                resourceIds.add(bookResourceDto.getResourceId());
            }

            // 调用应用中心获取资源基本信息
            Map<Long, ResourceDTO> passResourceMap = resourceConsr.mapByPass(resourceIds);
            if (!MapUtils.isEmpty(passResourceMap)) {
                for (Long resourceId : passResourceMap.keySet()) {
                    if (passResourceMap.get(resourceId) != null) {
                        ResourceDTO resourceDto = passResourceMap.get(resourceId);
                        resourceDto.setIsConvert(resourceDto.getConvertState());
                        passResource.add(resourceDto);
                    }
                }
            }

            // 调用分析引擎查询资源文件浏览量
            Map<Long, Long> pvOfAdviserRes = browseRecordConsr.getPvOfAdviserRes(resourceIds);
            if (!MapUtils.isEmpty(pvOfAdviserRes)) {
                for (ResourceDTO resourceDto : passResource) {
                    Long count = pvOfAdviserRes.get(resourceDto.getResourceId());
                    if (count == null) {
                        resourceDto.setCount(0);
                    } else {
                        resourceDto.setCount(count.intValue());
                    }
                }
            }
        }
        if (!ListUtils.isEmpty(passResource)) {
            resourceFiles.addAll(passResource);
        }
        return resourceFiles;
    }

    /**
     * 设置资源基本信息
     * @param bookResources
     */
    public void setResourceInfo(List<BookResourceDto> bookResources) {
        if (!ListUtils.isEmpty(bookResources)) {
            List<Long> resourceIds = new ArrayList<>();
            for (BookResourceDto bookResourceDto : bookResources) {
                resourceIds.add(bookResourceDto.getResourceId());
            }
            // 调用应用中心获取资源基本信息
            Map<Long, ResourceDTO> resources = resourceConsr.mapByIds(resourceIds);
            if (resources != null) {
                for (BookResourceDto bookResourceDto : bookResources) {
                    bookResourceDto.setResource(resources.get(bookResourceDto.getResourceId()));
                }
            }
        }
    }

    /**
     * 设置百分比
     * @param bookTypes
     */
    public void setPercent(List<BookTypeDto> bookTypes) {
        if (ListUtils.isEmpty(bookTypes)) {
            return;
        }
        Integer totalCount = 0;
        for (BookTypeDto bookTypeDto : bookTypes) {
            totalCount += bookTypeDto.getCount();
        }
        Double tempTotal = 0.00;
        for (int i = 0; i < bookTypes.size(); i++) {
            BookTypeDto bookTypeDto = bookTypes.get(i);
            if (totalCount == 0) {
                bookTypeDto.setPercent(0.00);
            } else {
                if (i == bookTypes.size() - 1) {
                    bookTypeDto.setPercent(AmountUtil.roundDown(100 - tempTotal));
                } else {
                    bookTypeDto.setPercent(AmountUtil.div(bookTypeDto.getCount() * 100, totalCount, 2));
                }

            }
            tempTotal += bookTypeDto.getPercent();
        }
    }

    /**
     * 设置模板名称
     * @param recordList
     */
    public void setTemplateName(List<Object> recordList) {
        LOGGER.info("设置模板名称【START】");
        if (ListUtils.isEmpty(recordList)) {
            return;
        }

        // 有二级列表优先展示二级列表,无则展示一级列表
        List<Long> templetIds = recordList.stream()
                .map(bookDto -> {
                    BookDto book = (BookDto) bookDto;
                    if (Objects.nonNull(book.getSecondTempletId())) {
                        return book.getSecondTempletId();
                    }
                    return book.getTempletId();
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        final Map<Long, AssistTempletDTO> assistTempletIds = assistTempletConsr.mapByIds(templetIds);

        if (MapUtils.isEmpty(assistTempletIds)) {
            LOGGER.info("设置模板名称【END】");
            return;
        }

        recordList.forEach(bookDto -> {
            BookDto book = (BookDto) bookDto;
            Long secondTempletId = book.getSecondTempletId();
            Long templetId = book.getTempletId();
            if (Objects.nonNull(secondTempletId)) {
                setBookDtoTempletInfo(assistTempletIds, book, secondTempletId);
            } else if (Objects.nonNull(templetId)) {
                setBookDtoTempletInfo(assistTempletIds, book, templetId);
            }
        });
        LOGGER.info("设置模板名称【END】");
    }

    private void setBookDtoTempletInfo(Map<Long, AssistTempletDTO> assistTempletIds, BookDto bookDto, Long secondTempletId) {
        AssistTempletDTO templetDTO = assistTempletIds.get(secondTempletId);
        bookDto.setTempletName(Optional.ofNullable(templetDTO).map(AssistTempletDTO::getTempletName).orElse(null));
        bookDto.setQrRemark(Optional.ofNullable(templetDTO).map(AssistTempletDTO::getRemark).orElse(null));
    }


    /**
     * 设置待审核数
     * @param recordList
     */
    public void setAuditWaitNum(List<Object> recordList) {
        LOGGER.info("设置待审核数【START】");
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> bookIds = Lists.newArrayList();
        for (Object object : recordList) {
            BookDto bookDto = (BookDto) object;
            if (bookDto.getBookId() != null) {
                bookIds.add(bookDto.getBookId());
            }
        }
        if (ListUtils.isEmpty(bookIds)) {
            return;
        }
        Map<Long, Long> resultMap = qrcodeSceneConsr.getCountMapByBookIds(bookIds);
        if (MapUtils.isEmpty(resultMap)) {
            return;
        }
        for (Object object : recordList) {
            BookDto bookDto = (BookDto) object;
            if (bookDto.getBookId() != null) {
                bookDto.setNoAuditNum(resultMap.get(bookDto.getBookId()));
            }
        }

    }

    /**
     * 设置模板名称
     * @param bookDto
     */
    public void setTemplateName(BookDto bookDto) {
        LOGGER.info("设置模板名称【START】");
        if (bookDto == null || bookDto.getTempletId() == null) {
            return;
        }
        List<Long> templetIds = new ArrayList<>();

        if (Objects.nonNull(bookDto.getSecondTempletId())) {
            templetIds.add(bookDto.getSecondTempletId());
        } else if (Objects.nonNull(bookDto.getTempletId())) {
            templetIds.add(bookDto.getTempletId());
        }

        Map<Long, AssistTempletDTO> assistTempletMap = assistTempletConsr.mapByIds(templetIds);
        if (MapUtils.isEmpty(assistTempletMap)) {
            return;
        }

        if (Objects.nonNull(bookDto.getSecondTempletId())) {
            setBookDtoTempletInfo(assistTempletMap, bookDto, bookDto.getSecondTempletId());
        } else if (Objects.nonNull(bookDto.getTempletId())) {
            setBookDtoTempletInfo(assistTempletMap, bookDto, bookDto.getTempletId());
        }

        LOGGER.info("设置模板名称【END】");
    }

    /**
     * 组合excel数据
     * @param agentBook
     * @return
     */
    public List<Object[]> getExcelData(List<Object> agentBook) {
        LOGGER.info("组合excel数据【START】");
        if (ListUtils.isEmpty(agentBook)) {
            return null;
        }
        Map<Long, Long> adviserIdsMap = new HashMap<>();
        Map<Long, Long> bookIdsMap = new HashMap<>();
        Map<Long, Long> channelIdsMap = new HashMap<>();
        List<Object[]> dataList = new ArrayList<Object[]>();
        for (Object object : agentBook) {
            BookDto bookDto = (BookDto) object;
            adviserIdsMap.put(bookDto.getAdviserId(), bookDto.getAdviserId());
            channelIdsMap.put(bookDto.getChannelId(), bookDto.getChannelId());
            bookIdsMap.put(bookDto.getBookId(), bookDto.getBookId());
        }
        List<Long> channelIds = Lists.newArrayList(channelIdsMap.values());
        List<Long> adviserIds = Lists.newArrayList(adviserIdsMap.values());
        List<Long> bookIds = Lists.newArrayList(bookIdsMap.values());
        // 调用用户中心获取运营名称
        Map<Long, String> channelNameMap = channelConsr.getNamesByIdList(channelIds);
        // 调用用户中心获取编辑名称
        Map<Long, String> adviserNameMap = adviserConsr.getNames(adviserIds);

        Map<String, BrowseCacheRecordDto> bookScanAndUv = browseRecordConsr.getBookScanAndUv(adviserIds, channelIds,
                bookIds);
        for (Object object : agentBook) {
            Object[] objs = new Object[6];
            BookDto bookDto = (BookDto) object;
            if (bookDto != null) {
                // 图书名称
                objs[0] = bookDto.getBookName() == null ? "" : bookDto.getBookName();
                String isbn = bookDto.getIsbn();
                String serialNumber = bookDto.getSerialNumber();
                if (!StringUtils.isEmpty(serialNumber)) {
                    isbn = isbn + "-" + serialNumber;
                }
                // 书刊条形码
                objs[1] = isbn == null ? "" : isbn;
                // 创建编辑
                if (adviserNameMap != null) {
                    String adviserName = adviserNameMap.get(bookDto.getAdviserId());
                    objs[2] = adviserName == null ? "" : adviserName;
                } else {
                    objs[2] = "";
                }
                // 运营平台
                if (channelNameMap != null) {
                    String channelName = channelNameMap.get(bookDto.getChannelId());
                    objs[3] = channelName == null ? "" : channelName;
                } else {
                    objs[3] = "";
                }

                Long browserCounts = 0L;
                Long scanCounts = 0L;
                if (bookScanAndUv != null) {
                    String key = bookDto.getBookId() + "-" + bookDto.getAdviserId() + "-" + bookDto.getChannelId();
                    BrowseCacheRecordDto browseCacheRecordDto = bookScanAndUv.get(key);
                    if (browseCacheRecordDto != null) {
                        browserCounts = browseCacheRecordDto.getBrowserCounts();
                        scanCounts = browseCacheRecordDto.getScanCount();
                    }
                }
                // 读者量
                objs[4] = browserCounts == null ? 0 : browserCounts;
                // 扫码量
                objs[5] = scanCounts == null ? 0 : scanCounts;
                dataList.add(objs);
            }
        }
        LOGGER.info(" 组合excel数据【END】");
        return dataList;
    }

    /**
     * 生成Excel
     * @param dataList
     * @return
     */
    public String createExcel(List<Object[]> dataList) {
        LOGGER.info("生成Excel【Start】");
        String[] rowsName = {"书刊名称", "书刊类型", "书刊分类", "条形码", "添加编辑", "出版社", "添加时间", "运营平台", "浏览量", "读者量", "扫码次数",
                "收益"};
        String fileUrl = exportConsr.exportExcel("编辑添加书刊列表-" + DateUtils.getStrFormTime("yyyyMMdd", new Date()),
                rowsName, dataList);
        LOGGER.info("生成Excel【END】fileUrl=" + fileUrl);
        return fileUrl;
    }

    /**
     * 发送图书Excel生成完成站内信
     * @param agentId
     * @param url
     * @param sendDate
     */
    public void sendBookExportLetter(Long agentId, String url, Date sendDate) {
        LOGGER.info("发送图书Excel生成完成站内信【Start】agentId=" + agentId + "url=" + url);
        String letterType = "book_download";
        JSONObject content = new JSONObject();
        content.put("commitTime", DateUtils.formatDate(sendDate));
        content.put("type", "图书导出");
        String fileName = DateUtils.today();
        messageConsr.sendLetter(agentId, agentId, content.toJSONString(), SystemCode.agent.code, letterType, url,
                fileName);
        LOGGER.info("发送图书Excel生成完成站内信【END】");
    }

    /**
     * 设置图书读者量、扫码量、浏览量
     * @param bookList
     */
    public void setBookSvUvPv(List<BookDto> bookList) {
        if (ListUtils.isEmpty(bookList)) {
            return;
        }
        Map<Long, Long> adviserIdsMap = new HashMap<>();
        Map<Long, Long> bookIdsMap = new HashMap<>();
        Map<Long, Long> channelIdsMap = new HashMap<>();
        for (BookDto bookDto : bookList) {
            adviserIdsMap.put(bookDto.getAdviserId(), bookDto.getAdviserId());
            channelIdsMap.put(bookDto.getChannelId(), bookDto.getChannelId());
            bookIdsMap.put(bookDto.getBookId(), bookDto.getBookId());
        }
        List<Long> channelIds = Lists.newArrayList(channelIdsMap.values());
        List<Long> adviserIds = Lists.newArrayList(adviserIdsMap.values());
        List<Long> bookIds = Lists.newArrayList(bookIdsMap.values());
        Map<String, BrowseCacheRecordDto> bookScanAndUv = browseRecordConsr.getBookScanAndUv(adviserIds, channelIds,
                bookIds);
        if (bookScanAndUv == null) {
            return;
        }
        for (BookDto bookDto : bookList) {
            String key = bookDto.getBookId() + "-" + bookDto.getAdviserId() + "-" + bookDto.getChannelId();
            BrowseCacheRecordDto browseCacheRecordDto = bookScanAndUv.get(key);
            if (browseCacheRecordDto != null) {
                bookDto.setBrowseCounts(browseCacheRecordDto.getBrowseCounts());
                bookDto.setBrowserCounts(browseCacheRecordDto.getBrowserCounts());
                bookDto.setScanCount(browseCacheRecordDto.getScanCount());
            }
        }
    }

    /**
     * 设置图书读者量、扫码量、浏览量
     * @param bookList
     */
    @ParamLog(value = "设置图书读者量、扫码量、浏览量", isBefore = false)
    public void setBookSvUvPv4Object(List<Object> bookList) {
        if (ListUtils.isEmpty(bookList)) {
            return;
        }
        Map<Long, Long> adviserIdsMap = new HashMap<>();
        Map<Long, Long> bookIdsMap = new HashMap<>();
        Map<Long, Long> channelIdsMap = new HashMap<>();
        for (Object object : bookList) {
            BookDto bookDto = (BookDto) object;
            adviserIdsMap.put(bookDto.getAdviserId(), bookDto.getAdviserId());
            channelIdsMap.put(bookDto.getChannelId(), bookDto.getChannelId());
            bookIdsMap.put(bookDto.getBookId(), bookDto.getBookId());
        }
        List<Long> channelIds = Lists.newArrayList(channelIdsMap.values());
        List<Long> adviserIds = Lists.newArrayList(adviserIdsMap.values());
        List<Long> bookIds = Lists.newArrayList(bookIdsMap.values());
        Map<String, BrowseCacheRecordDto> bookScanAndUv = browseRecordConsr.getBookScanAndUv(adviserIds, channelIds,
                bookIds);
        if (bookScanAndUv == null) {
            return;
        }
        for (Object object : bookList) {
            BookDto bookDto = (BookDto) object;
            String key = bookDto.getBookId() + "-" + bookDto.getAdviserId() + "-" + bookDto.getChannelId();
            BrowseCacheRecordDto browseCacheRecordDto = bookScanAndUv.get(key);
            if (browseCacheRecordDto != null) {
                bookDto.setBrowseCounts(browseCacheRecordDto.getBrowseCounts());
                bookDto.setBrowserCounts(browseCacheRecordDto.getBrowserCounts());
                bookDto.setScanCount(browseCacheRecordDto.getScanCount());
            }
        }
    }

    /**
     * 冻结状态
     * @param bookList
     */
    public void setFreezeStatus(List<Object> bookList) {
        if (ListUtils.isEmpty(bookList)) {
            return;
        }
        Map<Long, Long> bookIdsMap = new HashMap<>();
        for (Object object : bookList) {
            BookDto bookDto = (BookDto) object;
            if (bookDto != null && bookDto.getBookId() != null) {
                bookIdsMap.put(bookDto.getBookId(), bookDto.getBookId());
            }
        }
        List<Long> bookIds = Lists.newArrayList(bookIdsMap.values());
        if (CollectionUtils.isEmpty(bookIds)) {
            return;
        }
        // 设置基金冻结状态
        Map<Long, BookFreezeDto> freezeStatus = bookFreezeDao.getFreezeStatus(bookIds);
        for (Object object : bookList) {
            BookDto bookDto = (BookDto) object;
            if (bookDto != null) {
                if (freezeStatus != null && freezeStatus.get(bookDto.getBookId()) != null) {
                    bookDto.setFreezeStatus(BookFreezeEnum.FREEZE.value);
                }
            }
        }
    }

    /**
     * 设置冻结状态
     * @param bookDto
     */
    public void setFreezeStatus(BookDto bookDto) {
        if (bookDto != null) {
            Boolean freeze = bookFreezeDao.isFreeze(bookDto.getBookId());
            if (freeze) {
                bookDto.setFreezeStatus(BookFreezeEnum.FREEZE.value);
            }
        }

    }

    /**
     * 设置二维码相关信息
     * @param recordList
     */
    public void seBookGroupInfo(List<Object> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        for (Object object : recordList) {
            BookDto bookDto = (BookDto) object;
            if (null != bookDto.getIsBookGroup() && bookDto.getIsBookGroup()) {
                BookGroupDTO bookGroupDTO = bookGroupDao.getDTOByBookId(bookDto.getBookId(), bookDto.getChannelId(), bookDto.getAdviserId());
                if (null != bookGroupDTO) {
                    bookDto.setBookGroupId(bookGroupDTO.getId());
                    bookDto.setGroupQrcodeUrl(bookGroupDTO.getGroupQrcodeUrl());
                    bookDto.setGroupQrcodeName(bookGroupDTO.getGroupQrcodeName());
                    Map<Long, BookGroupStatisticDTO> statisMap = bookGroupClassifyDao.getClassifyCountAbout(Arrays.asList(bookGroupDTO.getId()));
                    if (!MapUtils.isEmpty(statisMap) && statisMap.containsKey(bookGroupDTO.getId())) {
                        BookGroupStatisticDTO statisticDTO = statisMap.get(bookGroupDTO.getId());
                        bookDto.setClassifyCount(null != statisticDTO.getClassifyCount() ? statisticDTO.getClassifyCount().longValue() : 0L);
                        bookDto.setGroupCount(null != statisticDTO.getGroupNumber() ? statisticDTO.getGroupNumber().longValue() : 0L);
                    } else {
                        bookDto.setClassifyCount(0L);
                        bookDto.setGroupCount(0L);
                    }
                }
            }
        }
    }

    /**
     * 设置社群书社群码相关信息
     * @param recordList
     */
    public void setQrInfo(List<Object> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<BookAssocLastQrAskVO> bookAssocLastQrAskVOS = Lists.newArrayList();
        BookAssocLastQrAskVO bookAssocLastQrAskVO = null;
        for (Object object : recordList) {
            BookDto bookDto = (BookDto) object;
            bookAssocLastQrAskVO = new BookAssocLastQrAskVO();
            bookAssocLastQrAskVO.setAdviserId(bookDto.getAdviserId());
            bookAssocLastQrAskVO.setBookId(bookDto.getBookId());
            bookAssocLastQrAskVO.setChannelId(bookDto.getChannelId());
            bookAssocLastQrAskVOS.add(bookAssocLastQrAskVO);
        }
        if (ListUtils.isEmpty(bookAssocLastQrAskVOS)) {
            return;
        }
        Map<String, BookAssocLastQrVO> bookAssocLastQrVOMap = qrcodeSceneConsr.getLastQrInfoByBookIds(bookAssocLastQrAskVOS);
        if (MapUtils.isEmpty(bookAssocLastQrVOMap)) {
            return;
        }
        for (Object object : recordList) {
            BookDto bookDto = (BookDto) object;
            String key = bookDto.getBookId() + "_" + bookDto.getChannelId();
            BookAssocLastQrVO bookAssocLastQrVO = bookAssocLastQrVOMap.get(key);
            if (null != bookAssocLastQrVO) {
                bookDto.setQrcodeUrl(bookAssocLastQrVO.getQrcodeUrl());
                bookDto.setMessageCount(bookAssocLastQrVO.getCount());
                List<QrcodeLocationDto> qrcodeLocationDtos = bookAssocLastQrVO.getQrcodeLocations();
                String localtion = null;
                if (!ListUtils.isEmpty(qrcodeLocationDtos)) {
                    localtion = StringUtil.isEmpty(qrcodeLocationDtos.get(0).getLocationName()) ? qrcodeLocationDtos.get(0).getLocationRemark() : qrcodeLocationDtos.get(0).getLocationName();
                }
                bookDto.setLocation(localtion);
                bookDto.setSceneName(bookAssocLastQrVO.getSceneName());
                bookDto.setSceneId(bookAssocLastQrVO.getSceneId());
                bookDto.setTypeCodeNames(bookAssocLastQrVO.getTypes());
            }
        }
    }

    /**
     * 设置图书收益
     * @param recordList
     */
    @ParamLog(value = "图书收益", isBefore = false)
    public void setBookIncome(List<Object> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> bookIdList = new ArrayList<>();
        List<Long> channelIdList = new ArrayList<>();
        List<Long> adviserIdList = new ArrayList<>();
        Long bookId = null;
        Long channelId = null;
        Long adviserId = null;
        String key = null;
        BigDecimal income = null;
        // 组合图书标识、渠道标识、编辑标识、键标识
        for (Object obj : recordList) {
            BookDto bookDto = (BookDto) obj;
            bookId = bookDto.getBookId();
            channelId = bookDto.getChannelId();
            adviserId = bookDto.getAdviserId();
            bookIdList.add(bookId);
            channelIdList.add(channelId);
            adviserIdList.add(adviserId);
        }
        if (ListUtils.isEmpty(adviserIdList) || ListUtils.isEmpty(channelIdList) || ListUtils.isEmpty(bookIdList)) {
            return;
        }
        Map<String, BigDecimal> incomeMap = bookConsr.getBookIncome(bookIdList, channelIdList, adviserIdList);
        // 设置图书收益，如果没有查到，则默认图书总收益为0
        if (incomeMap != null && !incomeMap.isEmpty()) {
            for (Object obj : recordList) {
                BookDto bookDto = (BookDto) obj;
                bookId = bookDto.getBookId();
                channelId = bookDto.getChannelId();
                adviserId = bookDto.getAdviserId();
                key = bookId + "-" + channelId + "-" + adviserId;
                income = incomeMap.get(key);
                if (income == null) {
                    bookDto.setIncome(new BigDecimal(0));
                }
                bookDto.setIncome(income);
            }
        }
    }

    /**
     * 发送图书Excel生成完成站内信(平台端)
     * @param
     * @param url
     * @param sendDate
     */
    public void sendBookExportLetter4Platform(long data, String url, Date sendDate) {
        LOGGER.info("发送图书Excel生成完成站内信【Start】data=" + data + "url=" + url);
        String letterType = "pcloud_book_download";
        String content = String.format("{\"commitTime\":\"%s\",\"type\":\"图书导出\"}", DateUtils.formatDate(sendDate));
        String fileName = DateUtils.today();
        messageConsr.sendLetter(data, 0L, content, SystemCode.pcloud.code, letterType, url, fileName);
        LOGGER.info("发送图书Excel生成完成站内信【END】");
    }

    /**
     * 组合excel数据(平台端)
     * @param platformBook
     * @return
     */
    public List<Object[]> getExcelData4Platform(List<Object> platformBook) {

        LOGGER.info("组合excel数据(平台端)【START】");
        if (ListUtils.isEmpty(platformBook)) {
            return null;
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        for (Object object : platformBook) {
            Object[] objs = new Object[12];
            BookDto bookDto = (BookDto) object;
            // 图书名称
            objs[0] = ((bookDto.getBookName() == null || "".equals(bookDto.getBookName())) ? ""
                    : bookDto.getBookName());
            // 书刊类型
            objs[1] = ((bookDto.getTypeName() == null || "".equals(bookDto.getTypeName().trim())) ? "-"
                    : bookDto.getTypeName());
            // 书刊分类
            objs[2] = ((bookDto.getTempletName() == null || "".equals(bookDto.getTempletName().trim())) ? "-"
                    : bookDto.getTempletName());
            // 条形码
            objs[3] = ((bookDto.getIsbn() == null || "".equals(bookDto.getIsbn().trim())) ? "-" : bookDto.getIsbn());
            // 添加编辑
            objs[4] = ((bookDto.getAdviserName() == null || "".equals(bookDto.getAdviserName().trim())) ? "-"
                    : bookDto.getAdviserName());
            // 出版社
            objs[5] = ((bookDto.getPublish() == null || "".equals(bookDto.getPublish().trim())) ? "-"
                    : bookDto.getPublish());
            // 添加时间
            objs[6] = bookDto.getCreatedDate() == null ? "-"
                    : DateUtils.getStrFormTime("yyyy/M/d H:m", bookDto.getCreatedDate());
            // 运营平台
            objs[7] = ((bookDto.getChannelName() == null || "".equals(bookDto.getChannelName().trim())) ? "-"
                    : bookDto.getChannelName());
            // 浏览量
            objs[8] = bookDto.getBrowseCounts() == null ? 0 : bookDto.getBrowseCounts();
            // 读者量
            objs[9] = bookDto.getBrowserCounts() == null ? 0 : bookDto.getBrowserCounts();
            // 扫码次数
            objs[10] = bookDto.getScanCount() == null ? 0 : bookDto.getScanCount();
            // 收益
            objs[11] = bookDto.getIncome() == null ? 0.0 : bookDto.getIncome();
            dataList.add(objs);
        }
        LOGGER.info("组合excel数据(平台端)【END】");
        return dataList;

    }

    /**
     * 设置图书是否关联二维码和个数
     * @param recordList (List<BookDto>)
     * @param adviserId  编辑标识
     */
    public void setIsRelationQrcodeAndCount(List<Object> recordList, Long adviserId) {
        LOGGER.info("设置图书关联二维码个数【START】");
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> channelIds = BookTools.listChannelIds(recordList);
        List<Long> bookIds = BookTools.listBookIds(recordList);

        Map<String, Long> bookQrCountMap = qrcodeSceneConsr.listBookQrCount(bookIds, channelIds, adviserId);

        for (Object obj : recordList) {
            BookDto bookDto = (BookDto) obj;
            if (null != bookDto) {
                String key = bookDto.getBookId() + "-" + bookDto.getChannelId();
                bookDto.setBookQrCount(0L);
                bookDto.setRelationQrcode(false);
                // 设置书籍二维码数
                if (null != bookQrCountMap) {
                    Long count = bookQrCountMap.get(key);
                    if (count != null && count > 0) {
                        bookDto.setBookQrCount(count);
                        bookDto.setRelationQrcode(true);
                    }
                }
                LOGGER.info("设置图书关联二维码个数【END】");
            }
        }
    }

    @ParamLog(value = "设置父模板标识", isBefore = false)
    public void setTempleParentId(BookDto bookDto) {
        if (null != bookDto && null != bookDto.getTempletId()) {
            List<Long> assistTempletIds = Lists.newArrayList();
            assistTempletIds.add(bookDto.getTempletId());
            Map<Long, AssistTempletDTO> templeMap = assistTempletConsr.mapByIds(assistTempletIds);
            if (!MapUtils.isEmpty(templeMap)) {
                AssistTempletDTO templetDTO = templeMap.get(bookDto.getTempletId());
                if (null != templetDTO) {
                    bookDto.setTempleParentId(templetDTO.getParentId());
                }
            }
        }
    }


    /**
     * 设置模板名称
     */
    public void setTempletNames(List<NoAuthBookVO> noAuthBookVOs) {
        if (ListUtils.isEmpty(noAuthBookVOs)) {
            return;
        }
        List<Long> templetIds = new ArrayList<Long>();
        for (NoAuthBookVO noAuthBookVO : noAuthBookVOs) {
            if (noAuthBookVO.getTempletId() != null) {
                templetIds.add(noAuthBookVO.getTempletId());
            }
        }
        Map<Long, AssistTempletDTO> assistTempletIds = assistTempletConsr.mapByIds(templetIds);
        if (!MapUtils.isEmpty(assistTempletIds)) {
            for (NoAuthBookVO noAuthBookVO : noAuthBookVOs) {
                if (noAuthBookVO.getTempletId() != null) {
                    AssistTempletDTO assistTempletDTO = assistTempletIds.get(noAuthBookVO.getTempletId());
                    if (assistTempletDTO != null) {
                        noAuthBookVO.setTempletName(assistTempletDTO.getTempletName());
                    }
                }
            }
        }
        LOGGER.info("设置模板名称【END】");
    }

    public void setChannelName(List<NoAuthBookVO> noAuthBookVOS) {
        // 组装运营标识(去重)
        List<Long> channelIds = BookTools.listChannelIds4NoAuthBookVO(noAuthBookVOS);
        // 从用户中心批量获取渠道名称
        Map<Long, String> channelNameMap = channelConsr.getNamesByIdList(channelIds);
        if (MapUtils.isEmpty(channelNameMap)) {
            return;
        }
        // 批量填充运营信息
        BookTools.setChannelNames4NoAuthBookVO(noAuthBookVOS, channelNameMap);
    }

    public void setAdviserInfo4BookDto(List<Object> objects) {
        // 组装编辑标识(去重)
        List<Long> adviserIds = BookTools.listAdviserIds(objects);
        // 从用户中心批量获取编辑名称
        Map<Long, AdviserBaseInfoDto> adviserMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(adviserIds);
        if (MapUtils.isEmpty(adviserMap)) {
            return;
        }
        // 批量填充编辑名称手机号
        for (Object object : objects) {
            BookDto bookDto = (BookDto) object;
            Long adviserId = bookDto.getAdviserId();
            if (adviserMap.containsKey(adviserId)) {
                bookDto.setAdviserName(adviserMap.get(adviserId).getPartyName());
                bookDto.setPhone(adviserMap.get(adviserId).getPhoneNum());
            } else {
                bookDto.setAdviserName("");
                bookDto.setPhone("");
            }
        }
    }
}
