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

import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.applet.dto.SpecialBookDTO;
import com.pcloud.book.applet.biz.SpecialBookBiz;
import com.pcloud.book.applet.dao.SpecialBookDao;
import com.pcloud.book.applet.entity.SpecialBook;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.common.ExportConsr;
import com.pcloud.book.consumer.message.MessageConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.book.consumer.user.AgentConsr;
import com.pcloud.book.consumer.user.ChannelConsr;
import com.pcloud.book.consumer.user.PartyConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.book.group.dto.BookServeDTO;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.SystemCode;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.readercenter.wechat.dto.SpecialBookDTO4Reader;
import com.pcloud.readercenter.wechat.dto.SpecialBookQueryDTO4Reader;
import com.pcloud.usercenter.party.agent.entity.Agent;
import com.pcloud.wechatgroup.group.dto.SpecialBookDTO4WG;
import com.pcloud.wechatgroup.group.dto.SpecialBookQueryDTO4WG;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (SpecialBook)表服务实现类
 *
 * @author makejava
 * @since 2020-09-16 13:43:43
 */
@Service("specialBookBiz")
public class SpecialBookBizImpl implements SpecialBookBiz {

    private static final Logger LOGGER = LoggerFactory.getLogger(SpecialBookBizImpl.class);

    @Autowired
    private SpecialBookDao specialBookDao;
    @Autowired
    private BookGroupBiz bookGroupBiz;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private ChannelConsr channelConsr;
    @Autowired
    private AgentConsr agentConsr;
    @Autowired
    private PartyConsr partyConsr;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private MessageConsr messageConsr;




    @Override
    @ParamLog("通过ID查询单条数据")
    public SpecialBook getById(Long id) {
        return specialBookDao.getById(id);
    }

    @Override
    @ParamLog("查询多条数据")
    public PageBeanNew getList(Integer currentPage, Integer numPerPage) {
        PageBeanNew pageBeanNew = specialBookDao.listPageNew(new PageParam(currentPage, numPerPage), null, "getList");
        List recordList = pageBeanNew.getRecordList();
        if (ListUtils.isEmpty(recordList)) {
            return pageBeanNew;
        }
        // 加载其它数据

        return pageBeanNew;
    }

    @Override
    @ParamLog("新增")
    public void insert(List<SpecialBook> specialBooks) {
        if (ListUtils.isEmpty(specialBooks)) {
            return;
        }
        List<Long> bookIds = specialBooks.stream().map(e -> e.getBookId()).collect(Collectors.toList());
        List<SpecialBook> specialBookList = specialBookDao.listByBookIds(bookIds);
        if (!ListUtils.isEmpty(specialBookList)) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,specialBookList.get(0).getBookName() + "已存在列表");
        }
        specialBookDao.insert(specialBooks);

    }

    @Override
    @ParamLog("修改")
    public void update(SpecialBook specialBook) {
        if (specialBook == null || !NumberUtil.isNumber(specialBook.getId())) {
            throw BizException.PARAM_IS_NULL;
        }
        specialBookDao.update(specialBook);
    }

    @Override
    @ParamLog("删除")
    public void deleteById(Long id) {
        specialBookDao.deleteById(id);
    }

    @Override
    @ParamLog(isAfterReturn = false)
    public PageBeanNew<SpecialBookDTO> listSpecialBook(String queryName, String startTime, String endTime, Integer currentPage, Integer numPerPage, String wechatUser) {
        Map<String, Object> paramMap = new HashMap<>();
        if (!StringUtil.isEmpty(queryName)) {
            paramMap.put("queryName", queryName);
        }
        List<Long> wechatUserIds = null;
        if (!StringUtil.isEmpty(wechatUser)) {
                wechatUserIds = readerConsr.getWechatUserByNameOrId(wechatUser);
            if (ListUtils.isEmpty(wechatUserIds)) {
                return  new PageBeanNew<>(currentPage, numPerPage,new ArrayList<>());
            }
        }
        if (!ListUtils.isEmpty(wechatUserIds)) {
            paramMap.put("wechatUserIds", wechatUserIds);
        }
        PageBeanNew<SpecialBookDTO> pageBeanNew = specialBookDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listSpecialBook");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return  pageBeanNew;
        }
        List<SpecialBookDTO> specialBookDTOS = pageBeanNew.getRecordList();
        List<Long> adviserIds = specialBookDTOS.stream().map(e -> e.getAdviserId()).collect(Collectors.toList());
        List<Long> channleIds = specialBookDTOS.stream().map(e -> e.getChannelId()).collect(Collectors.toList());
        List<Long> bookIds = specialBookDTOS.stream().map(e -> e.getBookId()).collect(Collectors.toList());
        List<Long> bookGroupIds = specialBookDTOS.stream().map(e -> e.getBookGroupId()).collect(Collectors.toList());
        Map<Long, String> adviserNameMap = new HashMap<>();
        Map<Long, String> channelNameMap = new HashMap<>();
        Map<Long, Agent> agentMap = new HashMap<>();
        if (!ListUtils.isEmpty(adviserIds)) {
            adviserNameMap = adviserConsr.getNames(adviserIds);
            agentMap = partyConsr.getAgentByPartyId(adviserIds, SystemCode.adviser.code);
        }
        if (!ListUtils.isEmpty(channleIds)) {
            channelNameMap = channelConsr.getNamesByIdList(channleIds);
        }
        SpecialBookQueryDTO4WG specialBookQueryDTO4WG = new SpecialBookQueryDTO4WG();
        specialBookQueryDTO4WG.setBookGroupIds(bookGroupIds);
        specialBookQueryDTO4WG.setStartTime(startTime);
        specialBookQueryDTO4WG.setEndTime(endTime);

        SpecialBookQueryDTO4Reader specialBookQueryDTO4Reader = new SpecialBookQueryDTO4Reader();
        specialBookQueryDTO4Reader.setBookIds(bookIds);
        specialBookQueryDTO4Reader.setStartTime(startTime);
        specialBookQueryDTO4Reader.setEndTime(endTime);



        Map<Long, SpecialBookDTO4WG> introductionPagePVMap  = wechatGroupConsr.getIntroductionPagePVAndUvMap(specialBookQueryDTO4WG);
        Map<Long, SpecialBookDTO4Reader> appletStatisticsMap = readerConsr.getAppletStatisticsMap(specialBookQueryDTO4Reader);
        for (SpecialBookDTO specialBookDTO : specialBookDTOS) {
            if (null != specialBookDTO.getAdviserId() && null != adviserNameMap.get(specialBookDTO.getAdviserId())) {
                specialBookDTO.setAdviserName(adviserNameMap.get(specialBookDTO.getAdviserId()));
                specialBookDTO.setAgentName(null != agentMap.get(specialBookDTO.getAdviserId()) ? agentMap.get(specialBookDTO.getAdviserId()).getName() : "");
            }
            if (null != specialBookDTO.getChannelId() && null != channelNameMap.get(specialBookDTO.getChannelId())) {
                specialBookDTO.setChannelName(channelNameMap.get(specialBookDTO.getChannelId()));
            }
            if (null != specialBookDTO.getBookGroupId() && null != introductionPagePVMap.get(specialBookDTO.getBookGroupId())) {
                specialBookDTO.setIntroductionPagePV(introductionPagePVMap.get(specialBookDTO.getBookGroupId()).getIntroductionPagePV());
                specialBookDTO.setIntroductionPageUV(introductionPagePVMap.get(specialBookDTO.getBookGroupId()).getIntroductionPageUV());
            }
            if (null != specialBookDTO.getBookId() && null != appletStatisticsMap.get(specialBookDTO.getBookId())) {
                specialBookDTO.setAppletNewUserCount(appletStatisticsMap.get(specialBookDTO.getBookId()).getAppletNewUserCount());
                specialBookDTO.setAppletPV(appletStatisticsMap.get(specialBookDTO.getBookId()).getAppletPV());
                specialBookDTO.setAppletUV(appletStatisticsMap.get(specialBookDTO.getBookId()).getAppletUV());
            }
            //资源数量
            List<BookServeDTO> serveDTOList = bookGroupBiz
                    .getBookAndBookGroupServeIds(specialBookDTO.getAdviserId(), specialBookDTO.getBookId(),
                            specialBookDTO.getChannelId());
            specialBookDTO.setResourceCount(ListUtils.isEmpty(serveDTOList) ? 0 : serveDTOList.size());
            DecimalFormat df = new DecimalFormat("0.00%");
            if (null ==  introductionPagePVMap.get(specialBookDTO.getBookGroupId()) || null == introductionPagePVMap.get(specialBookDTO.getBookGroupId()).getIntroductionPageUV() || 0 == introductionPagePVMap.get(specialBookDTO.getBookGroupId()).getIntroductionPageUV()
                    || null == appletStatisticsMap.get(specialBookDTO.getBookId()) || null == appletStatisticsMap.get(specialBookDTO.getBookId()).getAppletUV() || 0 == appletStatisticsMap.get(specialBookDTO.getBookId()).getAppletUV()) {
                specialBookDTO.setAppletTransformationEfficiency(df.format(0));
            } else {
                specialBookDTO.setAppletTransformationEfficiency(df.format(
                         appletStatisticsMap.get(specialBookDTO.getBookId()).getAppletUV().doubleValue()/introductionPagePVMap.get(specialBookDTO.getBookGroupId()).getIntroductionPageUV()
                        )
                );
            }
        }
        return pageBeanNew;
    }

    @Override
    public void exportSpecialBook(String queryName, String startTime, String endTime, Integer currentPage, Integer numPerPage, String wechatUser, Long partyId) {
        ThreadPoolUtils.EXPORT_THREAD_POOL.execute(() -> {
            PageBeanNew<SpecialBookDTO> specialBookDTOPageBeanNew = this.listSpecialBook(queryName, startTime, endTime, currentPage, numPerPage, wechatUser);
            if (null == specialBookDTOPageBeanNew || ListUtils.isEmpty(specialBookDTOPageBeanNew.getRecordList())) {
                return;
            }
            String exportSpecialBookUrl = getExportSpecialBookUrl(specialBookDTOPageBeanNew.getRecordList());
            String fileName = "书刊数据增长统计";
            if (!StringUtil.isEmpty(exportSpecialBookUrl)) {
                JSONObject content = new JSONObject();
                content.put("commitTime", DateUtils.formatDate(new Date()));
                content.put("type", "书刊数据增长统计导出");
                messageConsr.sendLetter(partyId, partyId, content.toJSONString(), SystemCode.pcloud.code, "book_download", exportSpecialBookUrl, fileName);
            }
        });

    }



    private String getExportSpecialBookUrl(List<SpecialBookDTO> list) {
        // 字段名
        String[] rowsName = {"书籍id", "书籍名称", "出版社名称", "isbn", "编辑名称", "渠道名称", "二维码", "资源数量", "落地页PV", "落地页UV", "小睿新增用户",
                "小睿浏览量PV", "小睿读者量UV", "进入小程序转化率"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < list.size(); i++) {
            SpecialBookDTO spaceDTO = list.get(i);
            objs = new Object[rowsName.length];
            objs[0] = spaceDTO.getBookId();
            objs[1] = spaceDTO.getBookName();
            objs[2] = spaceDTO.getAgentName();
            objs[3] = spaceDTO.getIsbn();
            objs[4] = spaceDTO.getAdviserName();
            objs[5] = spaceDTO.getChannelName();
            objs[6] = spaceDTO.getBookGroupUrl();
            objs[7] = spaceDTO.getResourceCount();
            objs[8] = null == spaceDTO.getIntroductionPagePV() ? 0 : spaceDTO.getIntroductionPagePV();
            objs[9] = null == spaceDTO.getIntroductionPageUV() ? 0 : spaceDTO.getIntroductionPageUV();
            objs[10] = null == spaceDTO.getAppletNewUserCount() ? 0 : spaceDTO.getAppletNewUserCount();
            objs[11] = null == spaceDTO.getAppletPV() ? 0 : spaceDTO.getAppletPV();
            objs[12] = null == spaceDTO.getAppletUV() ? 0 : spaceDTO.getAppletUV();
            objs[13] = null == spaceDTO.getAppletTransformationEfficiency() ? "0.00%" : spaceDTO.getAppletTransformationEfficiency();
            dataList.add(objs);
        }
        String fileName =new Date() + "落地页书刊数据统计";
        String fileUrl = exportConsr.exportExcel(fileName, rowsName, dataList);
        return fileUrl;
    }
}