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

import com.pcloud.book.applet.biz.AnswerSubscribeBiz;
import com.pcloud.book.applet.contants.AppletConstants;
import com.pcloud.book.applet.dao.AnswerSubscribeDao;
import com.pcloud.book.applet.dto.AnswerSubscribeDTO;
import com.pcloud.book.applet.entity.AnswerSubscribe;
import com.pcloud.book.applet.enums.AnswerSendStateEnum;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.message.TemplateConsr;
import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.book.group.dto.BookServeDTO;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.dto.AppletTemplateMessageDto;
import com.pcloud.common.enums.AppTypeEnum;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.string.StringUtil;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName com.pcloud.book.applet.biz.impl.AnswerSubscribeBizImpl
 * @Author zhuyajie
 * @Description 答案订阅
 * @Date 2020/9/16 16:23
 * @Version 1.0
 **/
@Component
@Slf4j
public class AnswerSubscribeBizImpl implements AnswerSubscribeBiz {

    @Autowired
    private AnswerSubscribeDao answerSubscribeDao;
    @Autowired
    private TemplateConsr templateConsr;
    @Autowired
    private BookGroupBiz bookGroupBiz;
    @Autowired
    private BookBiz bookBiz;

    @Override
    public void answerSubscribe(AnswerSubscribeDTO answerSubscribeDTO) {
        if (null == answerSubscribeDTO.getBookId() || null == answerSubscribeDTO.getAdviserId() ||
                null == answerSubscribeDTO.getChannelId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少书刊参数");
        }
        AnswerSubscribe answerSubscribe = new AnswerSubscribe();
        BeanUtils.copyProperties(answerSubscribeDTO, answerSubscribe);
        List<AnswerSubscribe> list = answerSubscribeDao.getRecordByUserBook(answerSubscribe);
        if (!ListUtils.isEmpty(list)) {
            return;
        }
        answerSubscribeDao.insert(answerSubscribe);
    }

    @Override
    public Map<String, Object> getSubscribeState(AnswerSubscribeDTO answerSubscribeDTO) {
        if (null == answerSubscribeDTO.getBookId() || null == answerSubscribeDTO.getAdviserId() ||
                null == answerSubscribeDTO.getChannelId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少书刊参数");
        }
        Boolean state = false;
        AnswerSubscribe answerSubscribe = new AnswerSubscribe();
        BeanUtils.copyProperties(answerSubscribeDTO, answerSubscribe);
        List<AnswerSubscribe> list = answerSubscribeDao.getRecordByUserBook(answerSubscribe);
        if (!ListUtils.isEmpty(list)) {
            state = true;
        }
        Boolean hasAnswer = hasAnswer(answerSubscribe.getBookId(), answerSubscribe.getAdviserId(), answerSubscribe.getChannelId());
        Map<String, Object> map = new HashMap<>();
        map.put("subscribeState", state);
        map.put("hasAnswer", hasAnswer);
        return map;
    }

    private Boolean hasAnswer(Long bookId, Long adviserId, Long channelId){
        //默认有答案
        Boolean hasAnswer = true;
        List<BookServeDTO> bookServeVOS = bookGroupBiz.getBookAndBookGroupServeIds(adviserId, bookId, channelId);
        bookGroupBiz.fillBookServe(bookServeVOS);
        bookGroupBiz.removeCanNotBuy(bookServeVOS);
        List<BookServeDTO> answerList = new ArrayList<>();
        if (!ListUtils.isEmpty(bookServeVOS)){
            answerList = bookServeVOS.stream().
                    filter(s -> AppTypeEnum.ANSWER.value.equals(s.getFromType()) || s.getServeName().contains("答案")).collect(Collectors.toList());
        }
        if (ListUtils.isEmpty(answerList)) {
            if ("pro".equals(BookProps.getSystemEnv()) && AppletConstants.NO_ANSWER_BOOK.contains(bookId)) {
                hasAnswer = false;
            } else if (!"pro".equals(BookProps.getSystemEnv())){
                hasAnswer = false;
            }
        }
        return hasAnswer;
    }

    @Override
    @ParamLog("发送答案订阅小程序模板消息")
    public void sendAppletMsg4Answer() {
        //待发送消息的书刊
        List<AnswerSubscribe> bookList = answerSubscribeDao.getBookBySendState(AnswerSendStateEnum.wait_send.code);
        if (ListUtils.isEmpty(bookList)) {
            return;
        }
        for (AnswerSubscribe answerSubscribeBook : bookList) {
            if ("pro".equals(BookProps.getSystemEnv()) && !AppletConstants.NO_ANSWER_BOOK.contains(answerSubscribeBook.getBookId())) {
                continue;
            }
            AnswerSubscribe subscribe = new AnswerSubscribe();
            subscribe.setSendState(AnswerSendStateEnum.wait_send.code);
            subscribe.setBookId(answerSubscribeBook.getBookId());
            subscribe.setChannelId(answerSubscribeBook.getChannelId());
            subscribe.setAdviserId(answerSubscribeBook.getAdviserId());
            List<AnswerSubscribe> userList = answerSubscribeDao.getBySendStateAndBook(subscribe);
            if (ListUtils.isEmpty(userList)) {
                continue;
            }
            BookDto bookDto = bookBiz.getBaseById(answerSubscribeBook.getBookId());
            if (null == bookDto) {
                continue;
            }
            List<BookServeDTO> bookServeVOS = bookGroupBiz.getBookAndBookGroupServeIds(answerSubscribeBook.getAdviserId(), answerSubscribeBook.getBookId(), answerSubscribeBook.getChannelId());
            bookGroupBiz.fillBookServe(bookServeVOS);
            bookGroupBiz.removeCanNotBuy(bookServeVOS);
            if (ListUtils.isEmpty(bookServeVOS)){
                continue;
            }
            List<BookServeDTO> answerList = bookServeVOS.stream().
                    filter(s -> AppTypeEnum.ANSWER.value.equals(s.getFromType()) || s.getServeName().contains("答案")).collect(Collectors.toList());
            if (ListUtils.isEmpty(answerList)) {
                continue;
            }
            for (AnswerSubscribe answerSubscribeUser : userList) {
                sendAppletTemplateMsg(answerSubscribeUser.getWechatUserId(), answerSubscribeUser.getAccountSettingId(),
                        bookDto.getBookName(), answerList.get(0).getServeName());
                //更新发送状态
                answerSubscribeUser.setSendState(AnswerSendStateEnum.has_send.code);
                answerSubscribeDao.updateSendState(answerSubscribeUser);
            }
        }
    }

    @Override
    @ParamLog("检测答案是否有提供")
    public void checkAnswerUpdate() {
        //已订阅的书
        List<AnswerSubscribe> list = answerSubscribeDao.getBookBySendState(AnswerSendStateEnum.subscribe.code);
        if (ListUtils.isEmpty(list)){
            return;
        }
        for (AnswerSubscribe answerSubscribe: list){
            Boolean hasAnswer = hasAnswer(answerSubscribe.getBookId(), answerSubscribe.getAdviserId(), answerSubscribe.getChannelId());
            if (hasAnswer){
                answerSubscribe.setSendState(AnswerSendStateEnum.wait_send.code);
                answerSubscribeDao.updateSendState(answerSubscribe);
            }
        }
    }

    private void sendAppletTemplateMsg(Long wechatUserId, Long accountSettingId, String bookName, String appName) {
        bookName = bookName.length() > 13 ? bookName.substring(0, 13) + "..." : bookName;
        appName = appName.length() > 13 ? appName.substring(0, 13) + "..." : appName;
        AppletTemplateMessageDto appletTemplateMessage;
        Map<String, String> tempMap;
        appletTemplateMessage = new AppletTemplateMessageDto();
        appletTemplateMessage.setAccountSettingId(accountSettingId);
        appletTemplateMessage.setWechatUserId(wechatUserId);
        appletTemplateMessage.setTempalteTypeCode("xiaorui_content_update_remind");
        appletTemplateMessage.setPage("pages/customize/index");
        tempMap = new HashMap<>();
        tempMap.put("thing4", "答案上架提醒");
        tempMap.put("thing10", StringUtil.addBracket(bookName));
        tempMap.put("thing9", appName);
        tempMap.put("date5", DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME));
        appletTemplateMessage.setData(tempMap);
        templateConsr.sendAppletMessageQueue(appletTemplateMessage);
    }

}
