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.UUIDUitl;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.commoncenter.user.track.domain.param.UserTrackEventContentDto;
import com.pcloud.commoncenter.user.track.domain.param.UserTrackEventDeviceDto;
import com.pcloud.commoncenter.user.track.domain.param.UserTrackEventEntryDto;
import com.pcloud.commoncenter.user.track.domain.param.UserTrackEventInfoDto;
import com.pcloud.commoncenter.user.track.domain.param.UserTrackEventParam;
import com.pcloud.commoncenter.user.track.domain.param.UserTrackEventUserDto;
import com.pcloud.commoncenter.user.track.sdk.UserTrackEventReportUtil;
import com.pcloud.readercenter.common.enums.YesOrNoNumEnum;
import com.pcloud.readercenter.common.utils.ReaderConstants;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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);
        } else {
            return 0L;
        }
        // 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);
            String sendKey = "subscribeCount" + UUIDUitl.taskName();
            Map<String,Object> contentExtraMap = new HashMap<>();
            contentExtraMap.put("spm",4149);
            contentExtraMap.put("subSpm",sendKey);
            UserTrackEventParam e = UserTrackEventParam.builder()
                    .parentId(null)
                    .device(UserTrackEventDeviceDto.builder().deviceImei("NA").deviceVersion("10.0").deviceExtra(new HashMap<>()).build())
                    .entry(UserTrackEventEntryDto.builder().entryType(null).entryVersion("1.0.0").entryExtra(null).build())
                    .event(UserTrackEventInfoDto.builder().eventCode("SEND_MSG").eventTime(new Date()).build())
                    .content(UserTrackEventContentDto.builder()
                            .officialId(ReaderConstants.MINI_OFFICIAL_ID)
                            .contentExtra(contentExtraMap)
                            .build())
                    .user(UserTrackEventUserDto.builder()
                            .userId(appletSubscribeRecord.getWechatUserId())
                            .build())
                    .build();
            UserTrackEventReportUtil.reportAndGetId(e);
            if (!sendState) {
                //发送公众号模板消息
                templateConsr.sendTempletMessage4Project("您的消息提醒次数已用完，请点击消息去新增", "新增后可及时接收他人点赞、回复等消息提醒",
                        appletSubscribeRecord.getWechatUserId(), "pages/notify/index", "订阅次数不足提醒", sendKey);
            } else {
                e.getContent().getContentExtra().put("spm",4150);
                e.getContent().getContentExtra().put("subSpm",sendKey + ":mini");
                UserTrackEventReportUtil.reportAndGetId(e);
            }

            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);
    }

}