package com.linkwechat.quartz.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.wecom.domain.WeCustomerMessageTimeTask;
import com.linkwechat.wecom.mapper.WeCustomerMessageTimeTaskMapper;
import com.linkwechat.wecom.service.IWeCustomerMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * @description: 群发任务推送
 * @author: HaoN
 * @create: 2021-05-31 10:43
 **/
@Slf4j
@Component("GroupPushTask")
public class GroupPushTask {

    @Autowired
    private WeCustomerMessageTimeTaskMapper customerMessageTimeTaskMapper;

    @Autowired
    private IWeCustomerMessageService weCustomerMessageService;

    /**
     * 扫描群发消息定时任务
     */
    public void messageTask() {
        //获的当前时间的毫秒数
        long currentTime = System.currentTimeMillis();
        //customerMessageTimeTaskMapper
        List<WeCustomerMessageTimeTask> weCustomerMessageTimeTasks = customerMessageTimeTaskMapper.selectWeCustomerMessageTimeTaskGteSettingTime(currentTime);

        final Semaphore semaphore = new Semaphore(5);

        if (CollectionUtils.isNotEmpty(weCustomerMessageTimeTasks)) {

            weCustomerMessageTimeTasks.forEach(
                    s -> {
                        try {
                            semaphore.acquire();
                            if (s.getMessageInfo() != null && s.getMessageId() != null || (s.getMessageInfo().getPushType().equals(WeConstans.SEND_MESSAGE_CUSTOMER)
                                    && CollectionUtils.isNotEmpty(s.getCustomersInfo())) || (s.getMessageInfo().getPushType().equals(WeConstans.SEND_MESSAGE_GROUP)
                                    && CollectionUtils.isNotEmpty(s.getGroupsInfo()))) {
                                weCustomerMessageService.sendMessgae(s.getMessageInfo(), s.getMessageId(), s.getCustomersInfo(), s.getGroupsInfo());
                                //更新消息处理状态
                                customerMessageTimeTaskMapper.updateTaskSolvedById(s.getTaskId());
                            }
                            semaphore.release();
                        } catch (JsonProcessingException | InterruptedException e) {
                            log.error("定时群发消息处理异常：ex:{}", e);
                            e.printStackTrace();
                        }
                    }
            );
        }

    }
}
