package com.liquidnet.service.sweet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.feign.kylin.api.FeignKylinPerformancesClient;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.sweet.config.WechatMaConfigure;
import com.liquidnet.service.sweet.dto.SweetAppletSubMsgOfTypeDto;
import com.liquidnet.service.sweet.entity.SweetAppletSubMsg;
import com.liquidnet.service.sweet.mapper.SweetAppletSubMsgMapper;
import com.liquidnet.service.sweet.service.ISweetAppletSubMsgService;
import com.liquidnet.service.sweet.utils.QueueUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 小程序订阅消息记录表 服务实现类
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-11-22
 */
@Service
@Slf4j
public class SweetAppletSubMsgServiceImpl extends ServiceImpl<SweetAppletSubMsgMapper, SweetAppletSubMsg> implements ISweetAppletSubMsgService {

    @Autowired
    private SweetAppletSubMsgMapper subMsgMapper;

    @Autowired
    @Lazy
    private FeignKylinPerformancesClient feignKylinPerformancesClient;

    @Autowired
    WechatMaConfigure wechatMaConfigure;

    @Autowired
    private QueueUtils queueUtils;

    @Autowired
    private SweetAppletSubMsgSendServiceImpl sweetAppletSubMsgSendService;

    private static final int pageSize = 2000;
    private static final int minusMinutes = 120;

    @Override
    public ResponseDto<Boolean> create(String openId, String unionId, String templateId, String targetId, Integer appletType, Integer activityType) {
        String[] templateIdArray = templateId.split(",");

        String uid = StringUtils.defaultString(CurrentUtil.getCurrentUid(), "");

        LinkedList<String> sqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
        sqls.add(SqlMapping.get("sweet_applet_sub_msg.insert"));
        for (String id : templateIdArray) {
            sqlsDataA.add(new Object[]{
                    IDGenerator.nextSnowId(), openId, unionId, uid, id, targetId, appletType, activityType
            });
        }
        queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_REMIND_INSERT.getKey(),
                SqlMapping.gets(sqls, sqlsDataA));

        return ResponseDto.success();
    }

    public ResponseDto sendMsg(Integer type) {
        List<SweetAppletSubMsgOfTypeDto> targetIds = subMsgMapper.selectListOfType(type);
        for (SweetAppletSubMsgOfTypeDto targetIdInfo : targetIds) {
            String targetId = targetIdInfo.getTargetId();
            ResponseDto<KylinPerformanceVo> kylinPerformanceVo = feignKylinPerformancesClient.detail(targetId, 0, 0, "");
            KylinPerformanceVo performanceVoData = kylinPerformanceVo.getData();
            if (null == performanceVoData || ObjectUtils.isEmpty(performanceVoData)) {
                log.info("无演出数据：[performancesId={}]", targetId);
                continue;
            }
            Integer isPush = isPush(performanceVoData, targetId);
            if (isPush != 3) {
                log.info("当前演出还不能推送：[状态={}]", isPush);
                continue;
            }
            String title = performanceVoData.getTitle();
            String timeStart = performanceVoData.getTimeStart();

            LambdaQueryWrapper<SweetAppletSubMsg> queryWrapper = Wrappers.lambdaQuery(SweetAppletSubMsg.class)
                    .eq(SweetAppletSubMsg::getIsPush, 1)
                    .eq(SweetAppletSubMsg::getActivityType, type)
                    .eq(SweetAppletSubMsg::getTargetId, targetId);
            Integer count = subMsgMapper.selectCount(queryWrapper);
            int countPage = (int) Math.ceil(count / pageSize);
            countPage = countPage + 1;

            for (int page = 0; page < countPage; page++) {
                List<SweetAppletSubMsg> msgList = subMsgMapper.selectList(
                        queryWrapper.last("LIMIT "
                                .concat(String.valueOf(page * pageSize))
                                .concat(",".concat(String.valueOf(pageSize)))
                        )
                );
                sweetAppletSubMsgSendService.toSend(msgList, targetId, title, timeStart);
            }
        }
        return ResponseDto.success();
    }

    @Override
    public ResponseDto sendOfActivityType(Integer activityType, String targetId, Integer timeType) {
        ResponseDto<KylinPerformanceVo> kylinPerformanceVo = feignKylinPerformancesClient.detail(targetId, 0, 0, "");
        KylinPerformanceVo performanceVoData = kylinPerformanceVo.getData();
        if (null == performanceVoData || ObjectUtils.isEmpty(performanceVoData)) {
            log.info("无演出数据：[performancesId={}]", targetId);
            return ResponseDto.failure("无演出数据");
        }
        if (timeType == 1) {
            Integer isPush = isPush(performanceVoData, targetId);
            if (isPush != 3) {
                return ResponseDto.failure("当前演出还不能推送，状态".concat(String.valueOf(isPush)));
            }
        }
        String title = performanceVoData.getTitle();
        String timeStart = performanceVoData.getTimeStart();

        LambdaQueryWrapper<SweetAppletSubMsg> queryWrapper = Wrappers.lambdaQuery(SweetAppletSubMsg.class)
                .eq(SweetAppletSubMsg::getIsPush, 1)
                .eq(SweetAppletSubMsg::getActivityType, activityType)
                .eq(SweetAppletSubMsg::getTargetId, targetId);
        Integer count = subMsgMapper.selectCount(queryWrapper);
        int countPage = (int) Math.ceil(count / pageSize);
        countPage = countPage + 1;

        for (int page = 0; page < countPage; page++) {
            List<SweetAppletSubMsg> msgList = subMsgMapper.selectList(
                    queryWrapper.last("LIMIT "
                            .concat(String.valueOf(page * pageSize))
                            .concat(",".concat(String.valueOf(pageSize)))
                    )
            );
            sweetAppletSubMsgSendService.toSend(msgList, targetId, title, timeStart);
        }
        return ResponseDto.success();
    }

    @Override
    public ResponseDto sendOfMid(String midList, String targetId, Integer timeType) {
        ResponseDto<KylinPerformanceVo> kylinPerformanceVo = feignKylinPerformancesClient.detail(targetId, 0, 0, "");
        KylinPerformanceVo performanceVoData = kylinPerformanceVo.getData();
        if (null == performanceVoData || ObjectUtils.isEmpty(performanceVoData)) {
            log.info("无演出数据：[performancesId={}]", targetId);
            return ResponseDto.failure("无演出数据");
        }
        if (timeType == 1) {
            Integer isPush = isPush(performanceVoData, targetId);
            if (isPush != 3) {
                return ResponseDto.failure("当前演出还不能推送，状态".concat(String.valueOf(isPush)));
            }
        }
        String title = performanceVoData.getTitle();
        String timeStart = performanceVoData.getTimeStart();

        String[] midListArray = midList.split(",");
        LambdaQueryWrapper<SweetAppletSubMsg> queryWrapper = Wrappers.lambdaQuery(SweetAppletSubMsg.class)
                .eq(SweetAppletSubMsg::getIsPush, 1)
                .in(SweetAppletSubMsg::getMid, midListArray);
        Integer count = subMsgMapper.selectCount(queryWrapper);
        int countPage = (int) Math.ceil(count / pageSize);
        countPage = countPage + 1;

        for (int page = 0; page < countPage; page++) {
            List<SweetAppletSubMsg> msgList = subMsgMapper.selectList(
                    queryWrapper.last("LIMIT "
                            .concat(String.valueOf(page * pageSize))
                            .concat(",".concat(String.valueOf(pageSize)))
                    )
            );
            sweetAppletSubMsgSendService.toSend(msgList, targetId, title, timeStart);
        }
        return ResponseDto.success();
    }

    /**
     * 判断演出时间 是否可以推送
     */
    private Integer isPush(KylinPerformanceVo performanceVoData, String targetId) {
        LocalDateTime nowTime = LocalDateTime.now();
        String nowTimeStr = DateUtil.Formatter.yyyyMMddHHmmss.format(nowTime);
        String sellTime = performanceVoData.getSellTime();
        LocalDateTime sellTimeLocal = LocalDateTime.parse(sellTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime sellTimeLocalNew = sellTimeLocal.minusMinutes(minusMinutes);
        String sellTimeLocalNewStr = DateUtil.Formatter.yyyyMMddHHmmss.format(sellTimeLocalNew);

        String stopSellTime = performanceVoData.getStopSellTime();
        if (1 == DateUtil.compareStrDay(nowTimeStr, stopSellTime)) { // 超过售卖期 不推 删redis
            log.info("超过售卖期：[nowTimeStr={}, stopSellTime={}, performancesId={}]", nowTimeStr, stopSellTime, targetId);
            return 1;
        }
        if (-1 == DateUtil.compareStrDay(nowTimeStr, sellTimeLocalNewStr)) { // 还没到售卖期
            log.info("还没到售卖期：[nowTimeStr={}, sellTimeLocalNewStr={}, performancesId={}]", nowTimeStr, sellTimeLocalNewStr, targetId);
            return 2;
        }
        return 3;
    }

}
