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


import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.book.service.BookService;
import com.pcloud.book.timecontrol.biz.BookTaskBindingBiz;
import com.pcloud.book.timecontrol.entity.TimeControlTask;
import com.pcloud.book.timecontrol.mapper.BookTaskBindingMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskSendMapper;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskSubscribeMapper;
import com.pcloud.book.timecontrol.vo.BookTaskBindingAddVO;
import com.pcloud.book.timecontrol.vo.BookTaskBindingVO;
import com.pcloud.common.dto.ResponseDto;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.labelcenter.label.service.LabelService;
import com.pcloud.wechatgroup.base.exception.WechatGroupBizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Gui_q
 * @since 2020年1月30日 17点27分
 */
@Component("bookTaskBindingBiz")
@Slf4j
public class BookTaskBindingBizImpl implements BookTaskBindingBiz {

    @Autowired
    private BookTaskBindingMapper bookTaskBindingMapper;

    @Autowired
    private BookService bookService;

    @Autowired
    private TimeControlTaskMapper timeControlTaskMapper;

    @Autowired
    private LabelService labelService;

    @Autowired
    private TimeControlTaskSendMapper timeControlTaskSendMapper;

    @Autowired
    private TimeControlTaskSubscribeMapper timeControlTaskSubscribeMapper;


    @Override
    public void create(BookTaskBindingAddVO bookTaskBindingAddVO) {

        // 查询图书是否与任务模板有过关联
        if (bookTaskBindingMapper.checkHasBinding(bookTaskBindingAddVO.getBookIds(), bookTaskBindingAddVO.getTaskId()) > 0) {
            throw new WechatGroupBizException(WechatGroupBizException.PARAM_IS_EXIST, "该书刊与任务已存在关联！");
        }

        TimeControlTask timeControlTask = timeControlTaskMapper.selectByPrimaryKey(bookTaskBindingAddVO.getTaskId());
        // 批量查询图书信息
        List<Integer> bookIds = bookTaskBindingAddVO.getBookIds();
        final List<Long> ids = bookIds.stream().map(Long::valueOf).collect(Collectors.toList());
        try {
            ResponseEntity<ResponseDto<Map<Long, BookDto>>> response = bookService.getListByIds(ids);
            Map<Long, BookDto> bookMap = ResponseHandleUtil.parseMap(response, Long.class, BookDto.class);
            // 批量插入
            bookTaskBindingMapper.batchInsert(new ArrayList<>(bookMap.values()), timeControlTask);
        } catch (Exception e) {
            log.error("bookService.getListByIds 批量获取书籍信息失败" + e.getMessage());
            throw new WechatGroupBizException(WechatGroupBizException.RESULT_NULL, "系统繁忙");
        }
    }

    @Override
    public PageBeanNew<BookTaskBindingVO> listBookTaskBinding4Pcloud(String book, Integer proLabelId, Integer depLabelId, Integer purLabelId, Integer currentPage, Integer numPerPage) {

        List<BookTaskBindingVO> list = new ArrayList<>();

        List<Integer> bookIds = null;
        // TODO 1. 根据社群码名称/书刊名称/ISBN/编号查询书籍ID列表
        try {
            ResponseEntity<ResponseDto<List<Long>>> response = bookService.getIdsByName(book);
            List<Long> ids = ResponseHandleUtil.parseList(response, Long.class);
            bookIds = ids.stream().map(item -> Integer.valueOf(item.intValue())).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("bookService.getListByIds 批量获取书籍信息失败" + e.getMessage());
        }

        Integer count = bookTaskBindingMapper.getBookTaskBindingCount(bookIds, proLabelId, depLabelId, purLabelId);
        if (count <= 0) {
            return new PageBeanNew<>(currentPage, numPerPage, count, list);
        }

        list = bookTaskBindingMapper.selectBookTaskBinding4Pcloud(bookIds, proLabelId, depLabelId, purLabelId, currentPage * numPerPage, numPerPage);

        String sendDay = DateUtils.getReqDate(new Date());
        // 补充统计数据
        list.forEach(item -> {
            item.setTaskCount(timeControlTaskSubscribeMapper.countTaskSubscribe(item.getTaskId(), item.getBookId()));
            item.setPreSendCount(timeControlTaskSendMapper.countTodayNotSend(item.getTaskId(), item.getBookId(), sendDay));
            item.setHasSentCount(timeControlTaskSendMapper.countMsgSend(item.getTaskId(), item.getBookId()));
        });

        // 封装标签 统计数据
        Set<Long> labelSet = new HashSet<>();
        // 获取所有标签 统一获取标签名称
        list.forEach(item -> {
            labelSet.add(item.getProLabelId());
            labelSet.add(item.getDepLabelId());
            labelSet.add(item.getPurLabelId());
        });

        labelSet.remove(null);
        if (labelSet.size() > 0) {
            try {
                // 批量获取标签名称
                ResponseEntity<ResponseDto<Map<Long, String>>> response = labelService.getLabelName(new ArrayList<>(labelSet));
                Map<Long, String> labelMap = ResponseHandleUtil.parseMap(response, Long.class, String.class);
                // 补充标签名称
                list.forEach(item -> {
                    item.setProLabelName(labelMap.get(item.getProLabelId()));
                    item.setDepLabelName(labelMap.get(item.getDepLabelId()));
                    item.setPurLabelName(labelMap.get(item.getPurLabelId()));
                });
            } catch (Exception e) {
                log.error("labelService.getLabelName 批量获取标签名称失败" + e.getMessage());
            }
        }

        return new PageBeanNew<>(currentPage, numPerPage, count, list);
    }

    @Override
    public void batchUpdateBookTaskState(List<Integer> ids, Integer state) {
        bookTaskBindingMapper.batchUpdateBookTaskState(ids, state);
    }

    @Override
    public void batchDeleteBookTask(List<Integer> ids) {
        bookTaskBindingMapper.batchDeleteBookTask(ids);
    }
}
