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

import com.pcloud.book.applet.biz.BuyBookRequestBiz;
import com.pcloud.book.applet.dao.BuyBookRequestDao;
import com.pcloud.book.applet.dto.BuyBookRequestDTO;
import com.pcloud.book.applet.dto.BuyBookRequetUserDTO;
import com.pcloud.book.applet.entity.BuyBookRequest;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.book.consumer.user.AgentConsr;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.readercenter.wechat.entity.WechatUser;
import org.apache.commons.collections.MapUtils;
import org.apache.regexp.RE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * (BuyBookRequest)表服务实现类
 *
 * @author makejava
 * @since 2020-10-14 19:51:41
 */
@Service("buyBookRequestBiz")
public class BuyBookRequestBizImpl implements BuyBookRequestBiz {

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

    @Autowired
    private BuyBookRequestDao buyBookRequestDao;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private BookBiz bookBiz;
    @Autowired
    private AgentConsr agentConsr;
    @Autowired
    private AdviserConsr adviserConsr;

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

    @Override
    @ParamLog("查询多条数据")
    public PageBeanNew getList(Integer currentPage, Integer numPerPage, Long agentId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId" , agentId);
        PageBeanNew pageBeanNew = buyBookRequestDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "getList");
        List<BuyBookRequestDTO> recordList = pageBeanNew.getRecordList();
        if (ListUtils.isEmpty(recordList)) {
            return pageBeanNew;
        }
        // 加载其它数据
        fillAgentInfo(recordList);
        return pageBeanNew;
    }

    private void fillAgentInfo(List<BuyBookRequestDTO> recordList) {
        List<Long> bookIds = recordList.stream().map(e -> e.getBookId()).collect(Collectors.toList());
        List<Long> agentIds = recordList.stream().map(e -> e.getAgentId()).collect(Collectors.toList());
        List<Long> adviserIds = recordList.stream().map(e -> e.getAdviserId()).collect(Collectors.toList());
        Map<Long, BookDto> bookDtoMap = new HashMap<>();
        Map<Long, String> agentNameMap = new HashMap<>();
        Map<Long, String> adviserNameMap = new HashMap<>();
        if (!ListUtils.isEmpty(bookIds)) {
            bookDtoMap = bookBiz.getListByIds(bookIds);
        }
        if (!ListUtils.isEmpty(agentIds)) {
            agentNameMap = agentConsr.getNames(agentIds);
        }
        if (!ListUtils.isEmpty(agentIds)) {
            adviserNameMap = adviserConsr.getNames(adviserIds);
        }
        for (BuyBookRequestDTO buyBookRequestDTO : recordList) {
            if (null == buyBookRequestDTO) {
                continue;
            }
            if (MapUtils.isNotEmpty(bookDtoMap) && null != bookDtoMap.get(buyBookRequestDTO.getBookId())) {
                buyBookRequestDTO.setBookName(bookDtoMap.get(buyBookRequestDTO.getBookId()).getBookName());
                buyBookRequestDTO.setCoverImg(bookDtoMap.get(buyBookRequestDTO.getBookId()).getCoverImg());
            }
            if (MapUtils.isNotEmpty(agentNameMap) && null != agentNameMap.get(buyBookRequestDTO.getAgentId())) {
                buyBookRequestDTO.setAgentName(agentNameMap.get(buyBookRequestDTO.getAgentId()));
            }
            if (MapUtils.isNotEmpty(adviserNameMap) && null != adviserNameMap.get(buyBookRequestDTO.getAdviserId())) {
                buyBookRequestDTO.setAdviserName(adviserNameMap.get(buyBookRequestDTO.getAdviserId()));
            }
        }


    }

    @Override
    @ParamLog("新增")
    public Long insert(BuyBookRequest buyBookRequest) {
        buyBookRequestDao.insert(buyBookRequest);
        return buyBookRequest.getId();
    }

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

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

    @Override
    public BuyBookRequetUserDTO getUserCount(Integer topCount) {
        List<BuyBookRequest> buyBookRequests =   buyBookRequestDao.getUserCount();
        BuyBookRequetUserDTO buyBookRequetUserDTO = new BuyBookRequetUserDTO();
        List<String> headUrls = new ArrayList<>();
        if (ListUtils.isEmpty(buyBookRequests)) {
            buyBookRequetUserDTO.setUserCount(0);
        } else {
            buyBookRequetUserDTO.setUserCount(buyBookRequests.size());
            List<Long> wechatUserIds = new ArrayList<>();
            wechatUserIds = buyBookRequests.stream().map(e -> e.getWechatUserId()).distinct().collect(Collectors.toList());
            if (!ListUtils.isEmpty(wechatUserIds)) {
                if (wechatUserIds.size() > topCount) {
                    wechatUserIds =  wechatUserIds.subList(0, topCount);
                }
                Map<Long, WechatUser> userList = readerConsr.getUserList(wechatUserIds);
                if (MapUtils.isNotEmpty(userList)) {
                    headUrls = userList.values().stream().map(e -> e.getWechatUserHeadurl()).collect(Collectors.toList());
                }
            }
        }
        buyBookRequetUserDTO.setUserCount(buyBookRequetUserDTO.getUserCount() < 3000 ? 300 + buyBookRequetUserDTO.getUserCount() : buyBookRequetUserDTO.getUserCount());
        buyBookRequetUserDTO.setWechatUserHeadUrl(headUrls);
        return buyBookRequetUserDTO;
    }



}