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

import com.alibaba.fastjson.JSONObject;
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.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.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.entity.WechatUser;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
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;

/**
 * (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;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private MessageConsr messageConsr;

    @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;
    }

    @Override
    public void exportRequestList(Long agentId, Integer currentPage, Integer numPerPage, Long partyId) {
        ThreadPoolUtils.EXPORT_THREAD_POOL.execute(() -> {
        PageBeanNew pageBeanNew = this.getList(currentPage, numPerPage, agentId);
        List<BuyBookRequestDTO> recordList = pageBeanNew.getRecordList();
        if (ListUtils.isEmpty(recordList)) {
            return ;
        }
        // 字段名
        String[] rowsName = {"书籍id", "书籍名称", "编辑名称", "出版社名称", "用户姓名", "手机号码", "收货地址", "申请时间"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < recordList.size(); i++) {
            BuyBookRequestDTO buyBookRequestDTO = recordList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = buyBookRequestDTO.getBookId();
            objs[1] = buyBookRequestDTO.getBookName();
            objs[2] = buyBookRequestDTO.getAdviserName();
            objs[3] = buyBookRequestDTO.getAgentName();
            objs[4] = buyBookRequestDTO.getUserName();
            objs[5] = buyBookRequestDTO.getPhone();
            objs[6] = buyBookRequestDTO.getAddress();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            objs[7] = null == buyBookRequestDTO.getCreateTime() ? "": simpleDateFormat.format(buyBookRequestDTO.getCreateTime());
            dataList.add(objs);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String fileName ="研发-购书申请表导出-" + simpleDateFormat.format(new Date());

        String fileUrl = exportConsr.exportExcel(fileName, rowsName, dataList);
        if (!StringUtil.isEmpty(fileUrl)) {
            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", fileUrl, fileName);
        }
    });
    }


}