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.dao.AnswerSubscribePopupDao;
import com.pcloud.book.applet.dto.AnswerSubscribeCountDto;
import com.pcloud.book.applet.dto.AnswerSubscribeDTO;
import com.pcloud.book.applet.dto.AnswerSubscribeUserDTO;
import com.pcloud.book.applet.entity.AnswerSubscribe;
import com.pcloud.book.applet.entity.AnswerSubscribeAdviser;
import com.pcloud.book.applet.entity.AnswerSubscribePopup;
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.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.message.TemplateConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.book.group.biz.ResourcePageBiz;
import com.pcloud.book.group.vo.ResourcePageVO;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.channelcenter.qrcode.dto.GroupQrcodeVO;
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 com.pcloud.readercenter.wechat.entity.WechatUserOfficialAccounts;

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 BookBiz bookBiz;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private AnswerSubscribeAdviserDao answerSubscribeAdviserDao;
    @Autowired
    private ResourcePageBiz resourcePageBiz;
    @Autowired
    private AnswerSubscribePopupDao answerSubscribePopupDao;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private ReaderConsr readerConsr;

    @Override
    public AnswerSubscribeDTO answerSubscribe(AnswerSubscribeDTO answerSubscribeDTO) {
        if (null == answerSubscribeDTO.getBookId() || null == answerSubscribeDTO.getAdviserId() ||
                null == answerSubscribeDTO.getChannelId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少书刊参数");
        }
        if (null == answerSubscribeDTO.getSubscribeType()) {
            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 new AnswerSubscribeDTO();
        }
        answerSubscribe.setResourceCount(resourcePageBiz.getResourceCounts(answerSubscribeDTO.getBookId(),answerSubscribeDTO.getAdviserId(),answerSubscribeDTO.getChannelId()));
        answerSubscribeDao.insert(answerSubscribe);
        //推送书刊埋点
        this.addSubscribePushRecord(answerSubscribeDTO);
        //关注公众号状态和公众号二维码
        AnswerSubscribeDTO dto = this.getSubscribeQrcodeState(answerSubscribeDTO.getWechatUserId(), answerSubscribeDTO.getAccountSettingId());
        return dto;
    }

    @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;
                }
                Integer resourceCount = resourcePageBiz.getResourceCounts(bookId, adviserId, channelId);
                if (resourceCount<=0){
                    continue;
                }
                String bookName = bookDto.getBookName();
                for (AnswerSubscribe answerSubscribeUser : userList) {
                    Long wechatUserId = answerSubscribeUser.getWechatUserId();
                    if (resourceCount <= answerSubscribeUser.getResourceCount()) {
                        //资源无新增，改为订阅未发送状态
                        answerSubscribeUser.setSendState(AnswerSendStateEnum.subscribe.code);
                    } else {
                        //资源有新增，发送消息
                        Long accountSettingId=answerSubscribeUser.getAccountSettingId();
                        if (BookProps.getMiniOfficialAccountsId().equals(accountSettingId)){
                         /* //小程序消息
                            this.sendAppletTemplateMsg(wechatUserId, accountSettingId,bookName);*/
                            continue;
                        } else {
                            //公众号消息
                            String url = getResourcePageUrl(bookId, adviserId, channelId);
                            this.sendTemplate4Customer(channelId,wechatUserId,bookName,url);
                        }
                        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) {
                Integer resourceCount = resourcePageBiz.getResourceCounts(answerSubscribe.getBookId(), answerSubscribe.getAdviserId(), answerSubscribe.getChannelId());
                if (resourceCount > 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);
    }

    @Override
    public AnswerSubscribeUserDTO getUserSubscribeInfo(Long wechatUserId) {
        AnswerSubscribeUserDTO answerSubscribeUserDTO = new AnswerSubscribeUserDTO();
        AnswerSubscribePopup popup = answerSubscribePopupDao.getLastRecord(wechatUserId);
        if (null == popup) {
            return answerSubscribeUserDTO;
        }
        answerSubscribeUserDTO.setBookId(popup.getBookId());
        answerSubscribeUserDTO.setChannelId(popup.getChannelId());
        answerSubscribeUserDTO.setAdviserId(popup.getAdviserId());
        //已关注公众号
        if (null != popup.getSubscribeType() && popup.getSubscribeType() == 1) {
            //推送链接
            answerSubscribeUserDTO.setUrl(getResourcePageUrl(popup.getBookId(), popup.getAdviserId(), popup.getChannelId()));
        }
        BookDto bookDto = bookBiz.getBaseById(popup.getBookId());
        answerSubscribeUserDTO.setBookName(null == bookDto ? null : bookDto.getBookName());
        return answerSubscribeUserDTO;
    }

    /**
     * 书刊开启小睿的资源页链接
     * @author：zhuyajie
     * @date：2021/6/3 15:06
     *  * @param null
     */
    private String getResourcePageUrl(Long bookId, Long adviserId, Long channelId) {
        String url = null;
        ResourcePageVO resourcePageVO = resourcePageBiz.getResourcePageByBookId(bookId, channelId, adviserId, null);
        if (null != resourcePageVO && resourcePageVO.getOpenRays() == 1) {
            String host = BookProps.getWechatDomain();
            if ("uat".equals(BookProps.getSystemEnv())) {
                host = host.replace("wechat666", "weixin35515");
            } else {
                host = host.replace("wechat666", "weixin23");
            }
            if (null != resourcePageVO.getSceneId()) {
                url = host + "/rayh5/book?sceneId=" + resourcePageVO.getSceneId();
            } else if (null != resourcePageVO.getBookGroupId()) {
                url = host + "/rayh5/book?bookGroupId=" + resourcePageVO.getId();
            }
        }
        return url;
    }

    @Override
    public AnswerSubscribeDTO getSubscribeQrcodeState(Long wechatUserId, Long accountSettingId) {
        String openId = readerConsr.getOpenIdByWechatUserIdAndOfficialAccountsId(wechatUserId, accountSettingId);
        WechatUserOfficialAccounts accounts = readerConsr.getOfficialAccounts(accountSettingId, openId, wechatUserId);
        Boolean isSubscribe = false;
        if (null != accounts) {
            isSubscribe = accounts.getIsSubscribe() == 1 ? true : false;
        }
        GroupQrcodeVO groupQrcodeVO = qrcodeSceneConsr.getSubscribeQrcode(accountSettingId);
        AnswerSubscribeDTO dto = new AnswerSubscribeDTO();
        dto.setQrcodeUrl(groupQrcodeVO.getQrcodeUrl());
        dto.setIsSubscribe(isSubscribe);
        return dto;
    }

    @Override
    public void addSubscribePushRecord(AnswerSubscribeDTO answerSubscribeDTO) {
        AnswerSubscribePopup popup = new AnswerSubscribePopup();
        popup.setWechatUserId(answerSubscribeDTO.getWechatUserId());
        popup.setAccountSettingId(answerSubscribeDTO.getAccountSettingId());
        popup.setBookId(answerSubscribeDTO.getBookId());
        popup.setChannelId(answerSubscribeDTO.getChannelId());
        popup.setAdviserId(answerSubscribeDTO.getAdviserId());
        popup.setSubscribeType(answerSubscribeDTO.getSubscribeType());
        answerSubscribePopupDao.insert(popup);
    }

    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, String url) {
        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, url, paramMap, SendType.SEND_BY_WECHAT_USER_ID.value, false);
    }
}
