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

import com.pcloud.book.applet.biz.AnswerSubscribeBiz;
import com.pcloud.book.applet.dao.AnswerSubscribeAdviserDao;
import com.pcloud.book.applet.dao.AnswerSubscribeDao;
import com.pcloud.book.applet.dto.AnswerSubscribeCountDto;
import com.pcloud.book.applet.dto.AnswerSubscribeDTO;
import com.pcloud.book.applet.entity.AnswerSubscribe;
import com.pcloud.book.applet.entity.AnswerSubscribeAdviser;
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.message.TemplateConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
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.constant.SceneCode;
import com.pcloud.common.core.constant.SendType;
import com.pcloud.common.core.constant.SystemCode;
import com.pcloud.common.core.dto.AppletTemplateMessageDto;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private AnswerSubscribeAdviserDao answerSubscribeAdviserDao;

    @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;
        }
        List<BookServeDTO> serveIds = bookGroupBiz.getBookAndBookGroupServeIds(answerSubscribeDTO.getAdviserId(), answerSubscribeDTO.getBookId(), answerSubscribeDTO.getChannelId());
        answerSubscribe.setResourceCount(serveIds.size());
        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;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("subscribeState", state);
        return map;
    }

    @Override
    @ParamLog("发送答案订阅小程序模板消息")
    public void sendAppletMsg4Answer() {
        //待发送消息的书刊
        List<AnswerSubscribe> bookList = answerSubscribeDao.getBookBySendState(AnswerSendStateEnum.wait_send.code);
        if (!ListUtils.isEmpty(bookList)) {
            for (AnswerSubscribe answerSubscribeBook : bookList) {
                Long adviserId = answerSubscribeBook.getAdviserId();
                Long channelId = answerSubscribeBook.getChannelId();
                Long bookId = answerSubscribeBook.getBookId();
                AnswerSubscribe subscribe = new AnswerSubscribe();
                subscribe.setSendState(AnswerSendStateEnum.wait_send.code);
                subscribe.setBookId(bookId);
                subscribe.setChannelId(channelId);
                subscribe.setAdviserId(adviserId);
                List<AnswerSubscribe> userList = answerSubscribeDao.getBySendStateAndBook(subscribe);
                if (ListUtils.isEmpty(userList)) {
                    continue;
                }
                BookDto bookDto = bookBiz.getBaseById(bookId);
                if (null == bookDto) {
                    continue;
                }
                List<BookServeDTO> serveIds = bookGroupBiz.getBookAndBookGroupServeIds(adviserId, bookId, channelId);
                if (ListUtils.isEmpty(serveIds)){
                    continue;
                }
                String bookName = bookDto.getBookName();
                for (AnswerSubscribe answerSubscribeUser : userList) {
                    Long wechatUserId = answerSubscribeUser.getWechatUserId();
                    if (serveIds.size() <= answerSubscribeUser.getResourceCount()) {
                        //资源无新增，改为订阅未发送状态
                        answerSubscribeUser.setSendState(AnswerSendStateEnum.subscribe.code);
                    } else {
                        //资源有新增，发送消息
                        Long accountSettingId=answerSubscribeUser.getAccountSettingId();
                        if (BookProps.getMiniOfficialAccountsId().equals(accountSettingId)){
                            //小程序消息
                            this.sendAppletTemplateMsg(wechatUserId, accountSettingId,bookName);
                        } else {
                            //公众号消息
                            this.sendTemplate4Customer(channelId,wechatUserId,bookName);
                        }
                        answerSubscribeUser.setSendState(AnswerSendStateEnum.has_send.code);
                    }
                    answerSubscribeDao.updateSendState(answerSubscribeUser);
                }
            }
        }
        //待发消息的编辑
        List<AnswerSubscribeAdviser> adviserList = answerSubscribeAdviserDao.getRecord4Send();
        if (!ListUtils.isEmpty(adviserList)){
            for (AnswerSubscribeAdviser answerSubscribeAdviser: adviserList){
                AnswerSubscribe subscribe = new AnswerSubscribe();
                subscribe.setBookId(answerSubscribeAdviser.getBookId());
                subscribe.setChannelId(answerSubscribeAdviser.getChannelId());
                subscribe.setAdviserId(answerSubscribeAdviser.getAdviserId());
                Integer userCount = answerSubscribeDao.getUserCountByBookAdviser(subscribe);
                BookDto bookDto = bookBiz.getBaseById(answerSubscribeAdviser.getBookId());
                if (null == bookDto) {
                    continue;
                }
                this.sendTemplateToAdviser(answerSubscribeAdviser.getAdviserId(), userCount, bookDto.getBookName(), answerSubscribeAdviser.getSendType());
                answerSubscribeAdviser.setSendState(1);
                answerSubscribeAdviserDao.update(answerSubscribeAdviser);
            }
        }
    }

    @Override
    @ParamLog("检测服务是否有新增")
    public void checkAnswerUpdate() {
        //已订阅的书
        List<AnswerSubscribe> list = answerSubscribeDao.getBookBySendState(AnswerSendStateEnum.subscribe.code);
        if (!ListUtils.isEmpty(list)) {
            for (AnswerSubscribe answerSubscribe : list) {
                List<BookServeDTO> serveIds = bookGroupBiz.getBookAndBookGroupServeIds(answerSubscribe.getAdviserId(), answerSubscribe.getBookId(), answerSubscribe.getChannelId());
                if (serveIds.size() > answerSubscribe.getResourceCount()) {
                    answerSubscribe.setSendState(AnswerSendStateEnum.wait_send.code);
                    answerSubscribeDao.updateSendState(answerSubscribe);
                }
            }
        }
        //检查订阅人数,10人
        List<AnswerSubscribeCountDto> countDtos = answerSubscribeDao.getSubscribeCount4Adviser(10);
        if (!ListUtils.isEmpty(countDtos)){
            for (AnswerSubscribeCountDto dto: countDtos){
                AnswerSubscribeAdviser query = new AnswerSubscribeAdviser();
                BeanUtils.copyProperties(dto,query);
                AnswerSubscribeAdviser subscribeAdviser = answerSubscribeAdviserDao.queryAll(query);
                if (null == subscribeAdviser){
                    query.setSendState(0);
                    query.setSendType(10);
                    answerSubscribeAdviserDao.insert(query);
                }
            }
        }
        //50人
        List<AnswerSubscribeCountDto> subscribeCountDtos = answerSubscribeDao.getSubscribeCount4Adviser(50);
        if (!ListUtils.isEmpty(subscribeCountDtos)) {
            for (AnswerSubscribeCountDto dto : subscribeCountDtos) {
                AnswerSubscribeAdviser query = new AnswerSubscribeAdviser();
                BeanUtils.copyProperties(dto, query);
                AnswerSubscribeAdviser subscribeAdviser = answerSubscribeAdviserDao.queryAll(query);
                if (null == subscribeAdviser) {
                    query.setSendState(0);
                    query.setSendType(50);
                    answerSubscribeAdviserDao.insert(query);
                    continue;
                }
                if (subscribeAdviser.getSendState() == 1 && subscribeAdviser.getSendType() == 50) {
                    continue;
                }
                subscribeAdviser.setSendState(0);
                subscribeAdviser.setSendType(50);
                answerSubscribeAdviserDao.update(subscribeAdviser);
            }
        }
    }

    @Override
    @ParamLog("取消本书服务关注")
    public void cancelAnswerSubscribe(AnswerSubscribeDTO answerSubscribeDTO) {
        if (null == answerSubscribeDTO.getBookId() || null == answerSubscribeDTO.getAdviserId() ||
                null == answerSubscribeDTO.getChannelId() || null == answerSubscribeDTO.getWechatUserId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少书刊参数");
        }
        answerSubscribeDao.cancelAnswerSubscribe(answerSubscribeDTO);
    }

    private void sendAppletTemplateMsg(Long wechatUserId, Long accountSettingId, String bookName) {
        bookName = bookName.length() > 13 ? bookName.substring(0, 13) + "..." : bookName;
        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", "本书有新的资源服务上架，是你想要的吗？");
        tempMap.put("date5", DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME));
        appletTemplateMessage.setData(tempMap);
        templateConsr.sendAppletMessageQueue(appletTemplateMessage);
    }

    private void sendTemplateToAdviser(Long adviserId, Integer userCount, String bookName, Integer sendType) {
        bookName = bookName.length() > 13 ? bookName.substring(0, 13) + "..." : bookName;
        Long agentId = adviserConsr.getAgentIdByAdviser(adviserId);
        String content = String.format("已有"+sendType+"人订阅了本书服务更新，很多人关注本书，建议尽快上架新服务！");
        Map<String, String> temParam = new HashMap<>();
        temParam.put("first", content);
        temParam.put("keyword1", "订阅" + StringUtil.addBracket(bookName));
        temParam.put("keyword2", "累计" + userCount + "人订阅了本书服务更新");
        temParam.put("remark", "如果有资源服务还没有上传，请尽快上传方便读者使用哦");
        templateConsr.sendManage(SceneCode.PROJECT_TASK_SCENE.value, agentId, adviserId, SystemCode.adviser.code, null, temParam, SendType.SEND_BY_PARTY_ID.value, false);
    }

    private void sendTemplate4Customer(Long channelId, Long wechatUserId, String bookName) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("first", "本书有新的资源服务上架，看看是不是你想要的？");
        paramMap.put("keyword1", StringUtil.addBracket(bookName));
        paramMap.put("keyword2", "书刊配套资源服务");
        paramMap.put("remark", "再次扫描书上二维码，即可查看更新内容");
        templateConsr.sendOperate(SceneCode.PROJECT_TASK_SCENE.value, channelId, wechatUserId, null, paramMap, SendType.SEND_BY_WECHAT_USER_ID.value, false);
    }
}
