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

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pcloud.book.applet.biz.AppletSubscribeCountBiz;
import com.pcloud.book.applet.biz.AppletSubscribeRecordBiz;
import com.pcloud.book.applet.dao.AppletSubscribeRecordDao;
import com.pcloud.book.applet.entity.AppletSubscribeCount;
import com.pcloud.book.applet.entity.AppletSubscribeRecord;
import com.pcloud.book.applet.enums.AppletRecordTypeEnum;
import com.pcloud.book.applet.enums.SubscribeCountTypeEnum;
import com.pcloud.book.applet.enums.SubscribeRecordTypeEnum;
import com.pcloud.book.consumer.message.TemplateConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.user.ChannelConsr;
import com.pcloud.book.cultivate.biz.CultivateNotifyBiz;
import com.pcloud.book.cultivate.dao.CultivateNotifyItemDao;
import com.pcloud.book.cultivate.dao.CultivateNotifySendDao;
import com.pcloud.book.cultivate.entity.CultivateNotify;
import com.pcloud.book.cultivate.entity.CultivateNotifyItem;
import com.pcloud.book.cultivate.entity.CultivateNotifySend;
import com.pcloud.book.cultivate.enums.NotifyMessageType;
import com.pcloud.book.cultivate.enums.NotifySendTypeEnum;
import com.pcloud.book.util.common.YesOrNoEnums;
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.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.cache.redis.JedisClusterUtils;
import com.pcloud.readercenter.common.enums.YesOrNoNumEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

import static com.pcloud.book.applet.contants.AppletConstants.APPLET_SEND_MESSAGE_COUNT;

/**
 * (AppletSubscribeRecord)表服务实现类
 *
 * @author wubo
 * @since 2021-08-03 09:37:01
 */
@Service("appletSubscribeRecordBiz")
public class AppletSubscribeRecordBizImpl implements AppletSubscribeRecordBiz {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppletSubscribeRecordBizImpl.class);

    @Autowired
    private AppletSubscribeRecordDao appletSubscribeRecordDao;
    @Autowired
    private AppletSubscribeCountBiz appletSubscribeCountBiz;
    @Autowired
    private TemplateConsr templateConsr;
    @Autowired
    private CultivateNotifyBiz cultivateNotifyBiz;
    @Autowired
    private CultivateNotifyItemDao cultivateNotifyItemDao;
    @Autowired
    private CultivateNotifySendDao cultivateNotifySendDao;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private ChannelConsr channelConsr;

    @Override
    @ParamLog("通过ID查询单条数据")
    public AppletSubscribeRecord getById(Long id) {
        return appletSubscribeRecordDao.getById(id);
    }


    @Override
    @ParamLog("查询多条数据")
    public PageBeanNew getList(Integer currentPage, Integer numPerPage) {
        PageBeanNew pageBeanNew = appletSubscribeRecordDao.listPageNew(new PageParam(currentPage, numPerPage), null, "getList");
        List recordList = pageBeanNew.getRecordList();
        if (ListUtils.isEmpty(recordList)) {
            return pageBeanNew;
        }
        // 加载其它数据

        return pageBeanNew;
    }

    @Override
    @ParamLog("新增")
    @Transactional(rollbackFor = Exception.class)
    public Long insert(AppletSubscribeRecord appletSubscribeRecord) {
        if (null == appletSubscribeRecord || null == appletSubscribeRecord.getRecordType()) {
           throw  new BizException(BizException.PARAM_IS_NULL.getCode(), "新增消息授权失败");
        }
        appletSubscribeRecordDao.insert(appletSubscribeRecord);
        //查询用户订阅次数
        Integer subscribeRecordCount = SubscribeCountTypeEnum.getCountByValue(appletSubscribeRecord.getCountType());
        AppletSubscribeCount subscribeCount = appletSubscribeCountBiz.getByUserId(appletSubscribeRecord.getWechatUserId(), appletSubscribeRecord.getRecordType());
        if (null == subscribeCount && subscribeRecordCount > 0) {
            subscribeCount = new AppletSubscribeCount();
            subscribeCount.setWechatUserId(appletSubscribeRecord.getWechatUserId());
            subscribeCount.setValidCount(YesOrNoEnums.YES.getValue());
            subscribeCount.setRecordType(appletSubscribeRecord.getRecordType());
            appletSubscribeCountBiz.insert(subscribeCount);
        } else if (null != subscribeCount){
            subscribeCount.setValidCount(subscribeCount.getValidCount() + subscribeRecordCount);
            if (subscribeCount.getValidCount() < 0) {
                subscribeCount.setValidCount(0);
            }
            appletSubscribeCountBiz.update(subscribeCount);
        }
        // 20220524 如果可用消息仅剩下1次，则发消息提醒
        sendMessageWhenOnlyOne(appletSubscribeRecord, subscribeRecordCount, subscribeCount);
        return appletSubscribeRecord.getId();
    }

    private void sendMessageWhenOnlyOne(AppletSubscribeRecord appletSubscribeRecord, Integer subscribeRecordCount, AppletSubscribeCount subscribeCount) {
        if (SubscribeCountTypeEnum.SUB_SUBSCRIBE.subscribeCount.equals(subscribeRecordCount) && APPLET_SEND_MESSAGE_COUNT.equals(subscribeCount.getValidCount())) {
            AppletTemplateMessageDto appletTemplateMessage = new AppletTemplateMessageDto();
            appletTemplateMessage.setAccountSettingId(BookProps.getMiniOfficialAccountsId());
            appletTemplateMessage.setWechatUserId(appletSubscribeRecord.getWechatUserId());
            appletTemplateMessage.setTempalteTypeCode("xiaorui_unread_message_remind");
            appletTemplateMessage.setPage("pages/notify/index");
            HashMap tempMap = Maps.newHashMap();
            tempMap.put("thing2", "您的消息提醒次数已用完，请点击消息去新增");
            tempMap.put("time3", DateUtils.getLongDateStr());
            tempMap.put("thing7", "新增后可及时接收他人点赞、回复等消息提醒");
            appletTemplateMessage.setData(tempMap);
            Boolean sendState = channelConsr.sendAppletMessage(appletTemplateMessage);
            if (!sendState) {
                //发送公众号模板消息
                templateConsr.sendTempletMessage4Project("您的消息提醒次数已用完，请点击消息去新增", "新增后可及时接收他人点赞、回复等消息提醒",
                        appletSubscribeRecord.getWechatUserId(), "pages/notify/index", "订阅次数不足提醒");
            }
            appletSubscribeRecordDao.insert(appletSubscribeRecord);
            subscribeCount.setValidCount(0);
            appletSubscribeCountBiz.update(subscribeCount);
            // 新增站内信
            CultivateNotify cultivateNotify=new CultivateNotify();
            cultivateNotify.setMessageType(NotifyMessageType.REMEMBER.code);
            cultivateNotify.setTitle("订阅消息次数不足提醒");
            cultivateNotify.setSendType(NotifySendTypeEnum.APPOINT_USER.value);
            cultivateNotify.setAgentId(0L);
            cultivateNotify.setCreateUserId(0L);
            cultivateNotifyBiz.insert(cultivateNotify);
             CultivateNotifyItem cultivateNotifyItem = new CultivateNotifyItem();
            cultivateNotifyItem.setMessageId(cultivateNotify.getMessageId());
            cultivateNotifyItem.setContentType(1);
            cultivateNotifyItem.setContent("订阅的通知次数已用完，后续将无法接受点赞、回复等消息提醒，请点击消息新增“订阅次数”");
            cultivateNotifyItemDao.insert(Lists.newArrayList(cultivateNotifyItem));
            //发给用户
            CultivateNotifySend notifySend = new CultivateNotifySend();
            notifySend.setMessageId(cultivateNotify.getMessageId());
            notifySend.setWechatUserId(appletSubscribeRecord.getWechatUserId());
            notifySend.setSendType(NotifySendTypeEnum.APPOINT_USER.value);
            notifySend.setMessageType(NotifyMessageType.REMEMBER.code);
            cultivateNotifySendDao.insert(notifySend);

        }
    }

    @Override
    @ParamLog("修改")
    public void update(AppletSubscribeRecord appletSubscribeRecord) {
        if (appletSubscribeRecord == null || !NumberUtil.isNumber(appletSubscribeRecord.getId())) {
            throw BizException.PARAM_IS_NULL;
        }
        appletSubscribeRecordDao.update(appletSubscribeRecord);
    }

    @Override
    @ParamLog("删除")
    public void deleteById(Long id) {
        appletSubscribeRecordDao.deleteById(id);
    }

    @Override
    @ParamLog("软删除")
    public void softDeleteById(Long id) {
        appletSubscribeRecordDao.softDeleteById(id);
    }

}